forked from Respect/Config
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContainer.php
More file actions
117 lines (94 loc) · 2.83 KB
/
Container.php
File metadata and controls
117 lines (94 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
declare(strict_types=1);
namespace Respect\Config;
use ArrayObject;
use Closure;
use Psr\Container\ContainerInterface;
use ReflectionException;
use function call_user_func;
use function class_exists;
use function is_callable;
/** @extends ArrayObject<string, mixed> */
class Container extends ArrayObject implements ContainerInterface
{
/** @param array<string, mixed> $definitions */
public function __construct(array $definitions = [])
{
foreach ($definitions as $key => $value) {
$this->offsetSet((string) $key, $value);
}
}
public function has(string $id): bool
{
if (!parent::offsetExists($id)) {
return false;
}
$entry = parent::offsetGet($id);
if ($entry instanceof Instantiator) {
return class_exists($entry->getClassName());
}
return true;
}
public function getItem(string $name, bool $raw = false): mixed
{
if (!parent::offsetExists($name)) {
throw new NotFoundException('Item ' . $name . ' not found');
}
$value = $this[$name];
if ($raw || !is_callable($value)) {
return $value;
}
try {
return $this->lazyLoad($name);
} catch (ReflectionException $e) {
throw new NotFoundException('Item ' . $name . ' not found: ' . $e->getMessage(), 0, $e);
}
}
public function get(string $id): mixed
{
return $this->getItem($id);
}
public function offsetSet(mixed $key, mixed $value): void
{
if ($value instanceof Autowire) {
$value->setContainer($this);
}
parent::offsetSet($key, $value);
}
public function set(string $name, mixed $value): void
{
$this[$name] = $value;
}
protected function lazyLoad(string $name): mixed
{
$callback = $this[$name];
if ($callback instanceof Instantiator) {
$result = $callback();
if ($callback->shouldCache()) {
$this[$name] = $result;
}
return $result;
}
if ($callback instanceof Closure) {
return $this[$name] = $callback($this);
}
return $this[$name] = call_user_func($callback);
}
public function __isset(string $name): bool
{
return $this->has($name);
}
public function __get(string $name): mixed
{
return $this->getItem($name);
}
public function __set(string $name, mixed $value): void
{
if (isset($this[$name]) && $this[$name] instanceof Instantiator) {
// Update the Instantiator's cached instance so other Instantiators
// holding a reference to it resolve to the new value
$this[$name]->setInstance($value);
}
$this[$name] = $value;
}
}