-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Di.php
164 lines (142 loc) · 5.3 KB
/
Di.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
<?php
declare(strict_types=1);
namespace Codeception\Lib;
use Codeception\Exception\InjectionException;
use Codeception\Util\ReflectionHelper;
use Exception;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use ReflectionObject;
class Di
{
/**
* @var string
*/
public const DEFAULT_INJECT_METHOD_NAME = '_inject';
/**
* @var object[]
*/
protected array $container = [];
protected ?Di $fallback = null;
public function __construct(Di $fallback = null)
{
$this->fallback = $fallback;
}
public function get(string $className): ?object
{
// normalize namespace
$className = ltrim($className, '\\');
return $this->container[$className] ?? null;
}
public function set(object $class): void
{
$this->container[$class::class] = $class;
}
/**
* @param string $injectMethodName Method which will be invoked after object creation;
* Resolved dependencies will be passed to it as arguments
* @throws InjectionException|ReflectionException
*/
public function instantiate(
string $className,
array $constructorArgs = null,
string $injectMethodName = self::DEFAULT_INJECT_METHOD_NAME
): ?object {
// normalize namespace
$className = ltrim($className, '\\');
// get class from container
if (isset($this->container[$className])) {
if ($this->container[$className] instanceof $className) {
return $this->container[$className];
}
throw new InjectionException("Failed to resolve cyclic dependencies for class '{$className}'");
}
// get class from parent container
if ($this->fallback && ($class = $this->fallback->get($className))) {
return $class;
}
$this->container[$className] = false; // flag that object is being instantiated
$reflectedClass = new ReflectionClass($className);
if (!$reflectedClass->isInstantiable()) {
return null;
}
$reflectedConstructor = $reflectedClass->getConstructor();
if (is_null($reflectedConstructor)) {
$object = new $className();
} else {
try {
if (!$constructorArgs) {
$constructorArgs = $this->prepareArgs($reflectedConstructor);
}
} catch (Exception $e) {
throw new InjectionException("Failed to create instance of '{$className}'. " . $e->getMessage());
}
$object = $reflectedClass->newInstanceArgs($constructorArgs);
}
if ($injectMethodName !== '') {
$this->injectDependencies($object, $injectMethodName);
}
$this->container[$className] = $object;
return $object;
}
/**
* @param string $injectMethodName Method which will be invoked with resolved dependencies as its arguments
* @throws InjectionException|ReflectionException
*/
public function injectDependencies(object $object, string $injectMethodName = self::DEFAULT_INJECT_METHOD_NAME, array $defaults = []): void
{
$reflectedObject = new ReflectionObject($object);
$reflectionObjectHasMethod = $reflectedObject->hasMethod($injectMethodName);
if (!$reflectionObjectHasMethod) {
return;
}
$reflectedMethod = $reflectedObject->getMethod($injectMethodName);
try {
$args = $this->prepareArgs($reflectedMethod, $defaults);
} catch (Exception $e) {
$msg = $e->getMessage();
if ($e->getPrevious() !== null) { // injection failed because PHP code is invalid. See #3869
$msg .= '; ' . $e->getPrevious();
}
throw new InjectionException(
"Failed to inject dependencies in instance of '{$reflectedObject->name}'. {$msg}"
);
}
if (!$reflectedMethod->isPublic()) {
$reflectedMethod->setAccessible(true);
}
$reflectedMethod->invokeArgs($object, $args);
}
protected function prepareArgs(ReflectionMethod $method, array $defaults = []): array
{
$args = [];
$parameters = $method->getParameters();
foreach ($parameters as $k => $parameter) {
$dependency = ReflectionHelper::getClassFromParameter($parameter);
if (is_null($dependency)) {
if ($parameter->isVariadic()) {
continue;
}
if (!$parameter->isOptional()) {
if (!isset($defaults[$k])) {
throw new InjectionException("Parameter '{$parameter->name}' must have default value.");
}
$args[] = $defaults[$k];
continue;
}
$args[] = $parameter->getDefaultValue();
} else {
$arg = $this->instantiate($dependency);
if (is_null($arg)) {
if ($parameter->isVariadic()) {
continue;
}
throw new InjectionException("Failed to resolve dependency '{$dependency}'.");
}
$args[] = $arg;
}
}
return $args;
}
}