1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Di; |
6
|
|
|
|
7
|
|
|
use Psr\Container\ContainerInterface; |
8
|
|
|
use Yiisoft\Factory\Exception\NotFoundException; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* This class implements a composite container for use with containers that support the delegate lookup feature. |
12
|
|
|
* The goal of the implementation is simplicity. |
13
|
|
|
*/ |
14
|
|
|
final class CompositeContainer implements ContainerInterface |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* Containers to look into starting from the beginning of the array. |
18
|
|
|
* |
19
|
|
|
* @var ContainerInterface[] The list of containers |
20
|
|
|
*/ |
21
|
|
|
private array $containers = []; |
22
|
|
|
|
23
|
28 |
|
public function get($id) |
24
|
|
|
{ |
25
|
28 |
|
if ($this->isTagAlias($id)) { |
26
|
2 |
|
$tags = []; |
27
|
2 |
|
foreach ($this->containers as $container) { |
28
|
2 |
|
if (!$container instanceof Container) { |
29
|
|
|
continue; |
30
|
|
|
} |
31
|
2 |
|
if ($container->has($id)) { |
32
|
2 |
|
$tags = array_merge($container->get($id), $tags); |
|
|
|
|
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
|
36
|
2 |
|
return $tags; |
37
|
|
|
} |
38
|
|
|
|
39
|
26 |
|
foreach ($this->containers as $container) { |
40
|
26 |
|
if ($container->has($id)) { |
41
|
23 |
|
return $container->get($id); |
42
|
|
|
} |
43
|
|
|
} |
44
|
5 |
|
throw new NotFoundException($id); |
45
|
|
|
} |
46
|
|
|
|
47
|
8 |
|
public function has($id): bool |
48
|
|
|
{ |
49
|
8 |
|
foreach ($this->containers as $container) { |
50
|
8 |
|
if ($container->has($id)) { |
51
|
8 |
|
return true; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
return false; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Attaches a container to the composite container. |
59
|
|
|
* |
60
|
|
|
* @param ContainerInterface $container |
61
|
|
|
*/ |
62
|
30 |
|
public function attach(ContainerInterface $container): void |
63
|
|
|
{ |
64
|
30 |
|
array_unshift($this->containers, $container); |
65
|
30 |
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Removes a container from the list of containers. |
69
|
|
|
* |
70
|
|
|
* @param ContainerInterface $container |
71
|
|
|
*/ |
72
|
2 |
|
public function detach(ContainerInterface $container): void |
73
|
|
|
{ |
74
|
2 |
|
foreach ($this->containers as $i => $c) { |
75
|
2 |
|
if ($container === $c) { |
76
|
2 |
|
unset($this->containers[$i]); |
77
|
|
|
} |
78
|
|
|
} |
79
|
2 |
|
} |
80
|
|
|
|
81
|
28 |
|
private function isTagAlias(string $id): bool |
82
|
|
|
{ |
83
|
28 |
|
return strpos($id, 'tag@') === 0; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|