1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Di; |
6
|
|
|
|
7
|
|
|
use Psr\Container\ContainerInterface; |
8
|
|
|
use Yiisoft\Factory\Exceptions\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
|
|
|
* @var ContainerInterface[] The list of containers |
19
|
|
|
*/ |
20
|
|
|
private array $containers = []; |
21
|
|
|
|
22
|
23 |
|
public function get($id) |
23
|
|
|
{ |
24
|
23 |
|
if ($this->isTagAlias($id)) { |
25
|
23 |
|
$tags = []; |
26
|
20 |
|
foreach ($this->containers as $container) { |
27
|
|
|
if (!$container instanceof Container) { |
28
|
|
|
continue; |
29
|
20 |
|
} |
30
|
|
|
if ($container->has($id)) { |
31
|
|
|
$tags = array_merge($container->get($id), $tags); |
|
|
|
|
32
|
5 |
|
} |
33
|
|
|
} |
34
|
|
|
|
35
|
8 |
|
return $tags; |
36
|
|
|
} |
37
|
8 |
|
|
38
|
8 |
|
foreach ($this->containers as $container) { |
39
|
8 |
|
if ($container->has($id)) { |
40
|
|
|
return $container->get($id); |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
throw new NotFoundException("No definition for $id"); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function has($id): bool |
47
|
|
|
{ |
48
|
|
|
foreach ($this->containers as $container) { |
49
|
25 |
|
if ($container->has($id)) { |
50
|
|
|
return true; |
51
|
25 |
|
} |
52
|
25 |
|
} |
53
|
|
|
return false; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Attaches a container to the composite container. |
58
|
2 |
|
* @param ContainerInterface $container |
59
|
|
|
*/ |
60
|
2 |
|
public function attach(ContainerInterface $container): void |
61
|
2 |
|
{ |
62
|
2 |
|
array_unshift($this->containers, $container); |
63
|
|
|
} |
64
|
|
|
|
65
|
2 |
|
/** |
66
|
|
|
* Removes a container from the list of containers. |
67
|
1 |
|
* @param ContainerInterface $container |
68
|
|
|
*/ |
69
|
|
|
public function detach(ContainerInterface $container): void |
70
|
|
|
{ |
71
|
|
|
foreach ($this->containers as $i => $c) { |
72
|
|
|
if ($container === $c) { |
73
|
|
|
unset($this->containers[$i]); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
private function isTagAlias(string $id): bool |
79
|
|
|
{ |
80
|
|
|
return strpos($id, 'tag@') === 0; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|