1 | <?php |
||
8 | class Bucket implements ContainerInterface |
||
9 | { |
||
10 | /** @var \Closure[] */ |
||
11 | private $factories = []; |
||
12 | |||
13 | /** @var array */ |
||
14 | private $values = []; |
||
15 | |||
16 | /** @var ContainerInterface */ |
||
17 | private $delegateContainer; |
||
18 | |||
19 | 18 | public function __construct(array $values = []) |
|
20 | { |
||
21 | 18 | foreach ($values as $id => $value) { |
|
22 | 3 | $this->add($id, $value); |
|
23 | } |
||
24 | 18 | } |
|
25 | |||
26 | /** |
||
27 | * @param string $id |
||
28 | * @param mixed $value |
||
29 | * |
||
30 | * @return self |
||
31 | */ |
||
32 | 15 | public function add(string $id, $value) |
|
33 | { |
||
34 | 15 | if ($value instanceof \Closure) { |
|
35 | 9 | return $this->addFactory($id, $value); |
|
36 | } |
||
37 | |||
38 | 6 | $this->values[$id] = $value; |
|
39 | |||
40 | 6 | return $this; |
|
41 | } |
||
42 | |||
43 | /** |
||
44 | * @param string $id |
||
45 | * @param \Closure $value |
||
46 | * |
||
47 | * @return self |
||
48 | */ |
||
49 | 9 | public function addFactory(string $id, \Closure $value) |
|
55 | |||
56 | /** |
||
57 | * @inheritdoc |
||
58 | */ |
||
59 | 18 | public function get($id) |
|
60 | { |
||
61 | 18 | if (!$this->has($id)) { |
|
62 | 3 | throw new NotFoundException('Item with id "' . $id . '" was not found.'); |
|
63 | } |
||
64 | |||
65 | 15 | if (!isset($this->values[$id])) { |
|
66 | 9 | $this->values[$id] = $this->getFromFactory($id); |
|
67 | } |
||
68 | |||
69 | 15 | return $this->values[$id]; |
|
70 | } |
||
71 | |||
72 | /** |
||
73 | * @param string $id |
||
74 | * @return mixed |
||
75 | */ |
||
76 | 9 | private function getFromFactory(string $id) |
|
77 | { |
||
78 | 9 | $factory = $this->factories[$id]; |
|
79 | 9 | $containerToUseForDependencies = $this->delegateContainer ?: $this; |
|
80 | |||
81 | 9 | return $factory($containerToUseForDependencies); |
|
82 | } |
||
83 | |||
84 | /** |
||
85 | * @inheritdoc |
||
86 | */ |
||
87 | 18 | public function has($id): bool |
|
91 | |||
92 | /** |
||
93 | * @param $id |
||
94 | * @return bool |
||
95 | */ |
||
96 | 18 | protected function hasFactory(string $id): bool |
|
100 | |||
101 | /** |
||
102 | * @param $id |
||
103 | * @return bool |
||
104 | */ |
||
105 | 9 | protected function hasValue(string $id): bool |
|
109 | |||
110 | /** |
||
111 | * @param ContainerInterface $delegateContainer |
||
112 | */ |
||
113 | 3 | public function setDelegateContainer(ContainerInterface $delegateContainer) |
|
117 | } |
||
118 |