-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGenericContainer.php
85 lines (74 loc) · 2.48 KB
/
GenericContainer.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
<?php
namespace Magium\Configuration\Container;
use Interop\Container\ContainerInterface;
class GenericContainer implements ContainerInterface
{
protected $container = [];
public function __construct(array $defaults = [])
{
$this->container = $defaults;
$this->set($this);
}
public function set($value)
{
if (!is_object($value)) {
throw new InvalidObjectException('The GenericContainer can only accept objects');
}
$class = new \ReflectionClass($value);
$interfaces = $class->getInterfaces();
foreach ($interfaces as $interface) {
if (!$interface->isInternal()) {
$this->container[$interface->getName()] = $value;
}
}
do {
if ($class->isInternal()) {
return; // Our work is done here.
}
$this->container[$class->getName()] = $value;
} while (($class = $class->getParentClass()) instanceof \ReflectionClass);
}
public function get($id)
{
if (!isset($this->container[$id])) {
$this->set($this->newInstance($id));
}
return $this->container[$id];
}
public function newInstance($type)
{
$reflection = new \ReflectionClass($type);
$constructor = $reflection->getConstructor();
$constructorParams = $this->getParams($constructor);
if ($constructorParams) {
$requestedInstance = $reflection->newInstanceArgs($constructorParams);
} else {
$requestedInstance = $reflection->newInstance();
}
return $requestedInstance;
}
protected function getParams(\ReflectionMethod $method = null)
{
if (!$method instanceof \ReflectionMethod) {
return [];
}
$constructorParams = [];
$params = $method->getParameters();
foreach ($params as $param) {
if ($param->getClass() instanceof \ReflectionClass) {
$class = $param->getClass()->getName();
$instance = $this->get($class);
$constructorParams[] = $instance;
} else if (!$param->isOptional()) {
throw new InvalidObjectException(
'The generic container will only manage constructor arguments that are objects'
);
}
}
return $constructorParams;
}
public function has($id)
{
return isset($this->container[$id]);
}
}