-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContainer.php
101 lines (87 loc) · 2.5 KB
/
Container.php
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
<?php
/**
* Qubus\Config
*
* @link https://github.com/QubusPHP/config
* @copyright 2020 Joshua Parker <josh@joshuaparker.blog>
* @copyright 2016 Sinergi
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
declare(strict_types=1);
namespace Qubus\Config;
use Psr\Container\ContainerInterface;
use ReflectionClass;
use function in_array;
use function is_array;
use function is_callable;
class Container implements ContainerInterface
{
public readonly ContainerInterface $diContainer;
/** @var array $container */
private array $container = [];
/** @var array $instances */
private array $instances = [];
public function __construct(ContainerInterface $diContainer)
{
$this->diContainer = $diContainer ;
}
/**
* @param mixed $id
*/
public function get($id)
{
if (isset($this->instances[$id])) {
return $this->instances[$id];
}
$className = $this->getContainerValue($id);
if (is_callable($className)) {
return $className($this->diContainer, $id);
}
$class = new $className();
return $this->instances[$id] = $class($this->diContainer);
}
/**
* @param mixed $id
*/
public function has($id): bool
{
if (isset($this->instances[$id])) {
return true;
}
return $this->getContainerValue($id) !== null;
}
protected function getContainerValue($id)
{
if (isset($this->container[$id])) {
return $this->container[$id];
}
foreach ($this->container as $alias => $concrete) {
$class = new ReflectionClass($id);
if (false === $class) {
return null;
}
do {
$name = $class->getName();
if ($alias === $name) {
return $concrete;
}
$interfaces = $class->getInterfaceNames();
if (is_array($interfaces) && in_array($alias, $interfaces)) {
return $concrete;
}
$class = $class->getParentClass();
} while (false !== $class);
return null;
}
return null;
}
public function add($alias, $className, $target = null): void
{
if (null === $target) {
$target = $className;
} else {
$this->container[$className] = $target;
}
$this->container[$alias] = $target;
}
}