1 | <?php |
||
2 | /** |
||
3 | * @link http://www.yiiframework.com/ |
||
4 | * @copyright Copyright (c) 2008 Yii Software LLC |
||
5 | * @license http://www.yiiframework.com/license/ |
||
6 | */ |
||
7 | |||
8 | namespace yii\di; |
||
9 | |||
10 | use ReflectionClass; |
||
11 | use ReflectionException; |
||
12 | use ReflectionNamedType; |
||
13 | use ReflectionParameter; |
||
14 | use Yii; |
||
15 | use yii\base\Component; |
||
16 | use yii\base\InvalidConfigException; |
||
17 | use yii\helpers\ArrayHelper; |
||
18 | |||
19 | /** |
||
20 | * Container implements a [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) container. |
||
21 | * |
||
22 | * A dependency injection (DI) container is an object that knows how to instantiate and configure objects and |
||
23 | * all their dependent objects. For more information about DI, please refer to |
||
24 | * [Martin Fowler's article](http://martinfowler.com/articles/injection.html). |
||
25 | * |
||
26 | * Container supports constructor injection as well as property injection. |
||
27 | * |
||
28 | * To use Container, you first need to set up the class dependencies by calling [[set()]]. |
||
29 | * You then call [[get()]] to create a new class object. Container will automatically instantiate |
||
30 | * dependent objects, inject them into the object being created, configure and finally return the newly created object. |
||
31 | * |
||
32 | * By default, [[\Yii::$container]] refers to a Container instance which is used by [[\Yii::createObject()]] |
||
33 | * to create new object instances. You may use this method to replace the `new` operator |
||
34 | * when creating a new object, which gives you the benefit of automatic dependency resolution and default |
||
35 | * property configuration. |
||
36 | * |
||
37 | * Below is an example of using Container: |
||
38 | * |
||
39 | * ```php |
||
40 | * namespace app\models; |
||
41 | * |
||
42 | * use yii\base\BaseObject; |
||
43 | * use yii\db\Connection; |
||
44 | * use yii\di\Container; |
||
45 | * |
||
46 | * interface UserFinderInterface |
||
47 | * { |
||
48 | * function findUser(); |
||
49 | * } |
||
50 | * |
||
51 | * class UserFinder extends BaseObject implements UserFinderInterface |
||
52 | * { |
||
53 | * public $db; |
||
54 | * |
||
55 | * public function __construct(Connection $db, $config = []) |
||
56 | * { |
||
57 | * $this->db = $db; |
||
58 | * parent::__construct($config); |
||
59 | * } |
||
60 | * |
||
61 | * public function findUser() |
||
62 | * { |
||
63 | * } |
||
64 | * } |
||
65 | * |
||
66 | * class UserLister extends BaseObject |
||
67 | * { |
||
68 | * public $finder; |
||
69 | * |
||
70 | * public function __construct(UserFinderInterface $finder, $config = []) |
||
71 | * { |
||
72 | * $this->finder = $finder; |
||
73 | * parent::__construct($config); |
||
74 | * } |
||
75 | * } |
||
76 | * |
||
77 | * $container = new Container; |
||
78 | * $container->set('yii\db\Connection', [ |
||
79 | * 'dsn' => '...', |
||
80 | * ]); |
||
81 | * $container->set('app\models\UserFinderInterface', [ |
||
82 | * 'class' => 'app\models\UserFinder', |
||
83 | * ]); |
||
84 | * $container->set('userLister', 'app\models\UserLister'); |
||
85 | * |
||
86 | * $lister = $container->get('userLister'); |
||
87 | * |
||
88 | * // which is equivalent to: |
||
89 | * |
||
90 | * $db = new \yii\db\Connection(['dsn' => '...']); |
||
91 | * $finder = new UserFinder($db); |
||
92 | * $lister = new UserLister($finder); |
||
93 | * ``` |
||
94 | * |
||
95 | * For more details and usage information on Container, see the [guide article on di-containers](guide:concept-di-container). |
||
96 | * |
||
97 | * @property-read array $definitions The list of the object definitions or the loaded shared objects (type or |
||
98 | * ID => definition or instance). This property is read-only. |
||
99 | * @property-write bool $resolveArrays Whether to attempt to resolve elements in array dependencies. This |
||
100 | * property is write-only. |
||
101 | * |
||
102 | * @author Qiang Xue <[email protected]> |
||
103 | * @since 2.0 |
||
104 | */ |
||
105 | class Container extends Component |
||
106 | { |
||
107 | /** |
||
108 | * @var array singleton objects indexed by their types |
||
109 | */ |
||
110 | private $_singletons = []; |
||
111 | /** |
||
112 | * @var array object definitions indexed by their types |
||
113 | */ |
||
114 | private $_definitions = []; |
||
115 | /** |
||
116 | * @var array constructor parameters indexed by object types |
||
117 | */ |
||
118 | private $_params = []; |
||
119 | /** |
||
120 | * @var array cached ReflectionClass objects indexed by class/interface names |
||
121 | */ |
||
122 | private $_reflections = []; |
||
123 | /** |
||
124 | * @var array cached dependencies indexed by class/interface names. Each class name |
||
125 | * is associated with a list of constructor parameter types or default values. |
||
126 | */ |
||
127 | private $_dependencies = []; |
||
128 | /** |
||
129 | * @var bool whether to attempt to resolve elements in array dependencies |
||
130 | */ |
||
131 | private $_resolveArrays = false; |
||
132 | |||
133 | |||
134 | /** |
||
135 | * Returns an instance of the requested class. |
||
136 | * |
||
137 | * You may provide constructor parameters (`$params`) and object configurations (`$config`) |
||
138 | * that will be used during the creation of the instance. |
||
139 | * |
||
140 | * If the class implements [[\yii\base\Configurable]], the `$config` parameter will be passed as the last |
||
141 | * parameter to the class constructor; Otherwise, the configuration will be applied *after* the object is |
||
142 | * instantiated. |
||
143 | * |
||
144 | * Note that if the class is declared to be singleton by calling [[setSingleton()]], |
||
145 | * the same instance of the class will be returned each time this method is called. |
||
146 | * In this case, the constructor parameters and object configurations will be used |
||
147 | * only if the class is instantiated the first time. |
||
148 | * |
||
149 | * @param string|Instance $class the class Instance, name or an alias name (e.g. `foo`) that was previously |
||
150 | * registered via [[set()]] or [[setSingleton()]]. |
||
151 | * @param array $params a list of constructor parameter values. Use one of two definitions: |
||
152 | * - Parameters as name-value pairs, for example: `['posts' => PostRepository::class]`. |
||
153 | * - Parameters in the order they appear in the constructor declaration. If you want to skip some parameters, |
||
154 | * you should index the remaining ones with the integers that represent their positions in the constructor |
||
155 | * parameter list. |
||
156 | * Dependencies indexed by name and by position in the same array are not allowed. |
||
157 | * @param array $config a list of name-value pairs that will be used to initialize the object properties. |
||
158 | * @return object an instance of the requested class. |
||
159 | * @throws InvalidConfigException if the class cannot be recognized or correspond to an invalid definition |
||
160 | * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
||
161 | */ |
||
162 | 5158 | public function get($class, $params = [], $config = []) |
|
163 | { |
||
164 | 5158 | if ($class instanceof Instance) { |
|
165 | 1 | $class = $class->id; |
|
166 | } |
||
167 | 5158 | if (isset($this->_singletons[$class])) { |
|
168 | // singleton |
||
169 | 4 | return $this->_singletons[$class]; |
|
170 | 5158 | } elseif (!isset($this->_definitions[$class])) { |
|
171 | 5155 | return $this->build($class, $params, $config); |
|
172 | } |
||
173 | |||
174 | 37 | $definition = $this->_definitions[$class]; |
|
175 | |||
176 | 37 | if (is_callable($definition, true)) { |
|
177 | 7 | $params = $this->resolveDependencies($this->mergeParams($class, $params)); |
|
178 | 7 | $object = call_user_func($definition, $this, $params, $config); |
|
179 | 33 | } elseif (is_array($definition)) { |
|
180 | 32 | $concrete = $definition['class']; |
|
181 | 32 | unset($definition['class']); |
|
182 | |||
183 | 32 | $config = array_merge($definition, $config); |
|
184 | 32 | $params = $this->mergeParams($class, $params); |
|
185 | |||
186 | 32 | if ($concrete === $class) { |
|
187 | 4 | $object = $this->build($class, $params, $config); |
|
188 | } else { |
||
189 | 32 | $object = $this->get($concrete, $params, $config); |
|
190 | } |
||
191 | 2 | } elseif (is_object($definition)) { |
|
192 | 2 | return $this->_singletons[$class] = $definition; |
|
193 | } else { |
||
194 | throw new InvalidConfigException('Unexpected object definition type: ' . gettype($definition)); |
||
195 | } |
||
196 | |||
197 | 33 | if (array_key_exists($class, $this->_singletons)) { |
|
198 | // singleton |
||
199 | 5 | $this->_singletons[$class] = $object; |
|
200 | } |
||
201 | |||
202 | 33 | return $object; |
|
203 | } |
||
204 | |||
205 | /** |
||
206 | * Registers a class definition with this container. |
||
207 | * |
||
208 | * For example, |
||
209 | * |
||
210 | * ```php |
||
211 | * // register a class name as is. This can be skipped. |
||
212 | * $container->set('yii\db\Connection'); |
||
213 | * |
||
214 | * // register an interface |
||
215 | * // When a class depends on the interface, the corresponding class |
||
216 | * // will be instantiated as the dependent object |
||
217 | * $container->set('yii\mail\MailInterface', 'yii\swiftmailer\Mailer'); |
||
218 | * |
||
219 | * // register an alias name. You can use $container->get('foo') |
||
220 | * // to create an instance of Connection |
||
221 | * $container->set('foo', 'yii\db\Connection'); |
||
222 | * |
||
223 | * // register a class with configuration. The configuration |
||
224 | * // will be applied when the class is instantiated by get() |
||
225 | * $container->set('yii\db\Connection', [ |
||
226 | * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', |
||
227 | * 'username' => 'root', |
||
228 | * 'password' => '', |
||
229 | * 'charset' => 'utf8', |
||
230 | * ]); |
||
231 | * |
||
232 | * // register an alias name with class configuration |
||
233 | * // In this case, a "class" element is required to specify the class |
||
234 | * $container->set('db', [ |
||
235 | * 'class' => 'yii\db\Connection', |
||
236 | * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', |
||
237 | * 'username' => 'root', |
||
238 | * 'password' => '', |
||
239 | * 'charset' => 'utf8', |
||
240 | * ]); |
||
241 | * |
||
242 | * // register a PHP callable |
||
243 | * // The callable will be executed when $container->get('db') is called |
||
244 | * $container->set('db', function ($container, $params, $config) { |
||
245 | * return new \yii\db\Connection($config); |
||
246 | * }); |
||
247 | * ``` |
||
248 | * |
||
249 | * If a class definition with the same name already exists, it will be overwritten with the new one. |
||
250 | * You may use [[has()]] to check if a class definition already exists. |
||
251 | * |
||
252 | * @param string $class class name, interface name or alias name |
||
253 | * @param mixed $definition the definition associated with `$class`. It can be one of the following: |
||
254 | * |
||
255 | * - a PHP callable: The callable will be executed when [[get()]] is invoked. The signature of the callable |
||
256 | * should be `function ($container, $params, $config)`, where `$params` stands for the list of constructor |
||
257 | * parameters, `$config` the object configuration, and `$container` the container object. The return value |
||
258 | * of the callable will be returned by [[get()]] as the object instance requested. |
||
259 | * - a configuration array: the array contains name-value pairs that will be used to initialize the property |
||
260 | * values of the newly created object when [[get()]] is called. The `class` element stands for the |
||
261 | * the class of the object to be created. If `class` is not specified, `$class` will be used as the class name. |
||
262 | * - a string: a class name, an interface name or an alias name. |
||
263 | * @param array $params the list of constructor parameters. The parameters will be passed to the class |
||
264 | * constructor when [[get()]] is called. |
||
265 | * @return $this the container itself |
||
266 | */ |
||
267 | 1043 | public function set($class, $definition = [], array $params = []) |
|
268 | { |
||
269 | 1043 | $this->_definitions[$class] = $this->normalizeDefinition($class, $definition); |
|
270 | 1043 | $this->_params[$class] = $params; |
|
271 | 1043 | unset($this->_singletons[$class]); |
|
272 | 1043 | return $this; |
|
273 | } |
||
274 | |||
275 | /** |
||
276 | * Registers a class definition with this container and marks the class as a singleton class. |
||
277 | * |
||
278 | * This method is similar to [[set()]] except that classes registered via this method will only have one |
||
279 | * instance. Each time [[get()]] is called, the same instance of the specified class will be returned. |
||
280 | * |
||
281 | * @param string $class class name, interface name or alias name |
||
282 | * @param mixed $definition the definition associated with `$class`. See [[set()]] for more details. |
||
283 | * @param array $params the list of constructor parameters. The parameters will be passed to the class |
||
284 | * constructor when [[get()]] is called. |
||
285 | * @return $this the container itself |
||
286 | * @see set() |
||
287 | */ |
||
288 | 10 | public function setSingleton($class, $definition = [], array $params = []) |
|
289 | { |
||
290 | 10 | $this->_definitions[$class] = $this->normalizeDefinition($class, $definition); |
|
291 | 10 | $this->_params[$class] = $params; |
|
292 | 10 | $this->_singletons[$class] = null; |
|
293 | 10 | return $this; |
|
294 | } |
||
295 | |||
296 | /** |
||
297 | * Returns a value indicating whether the container has the definition of the specified name. |
||
298 | * @param string $class class name, interface name or alias name |
||
299 | * @return bool whether the container has the definition of the specified name.. |
||
300 | * @see set() |
||
301 | */ |
||
302 | 9 | public function has($class) |
|
303 | { |
||
304 | 9 | return isset($this->_definitions[$class]); |
|
305 | } |
||
306 | |||
307 | /** |
||
308 | * Returns a value indicating whether the given name corresponds to a registered singleton. |
||
309 | * @param string $class class name, interface name or alias name |
||
310 | * @param bool $checkInstance whether to check if the singleton has been instantiated. |
||
311 | * @return bool whether the given name corresponds to a registered singleton. If `$checkInstance` is true, |
||
312 | * the method should return a value indicating whether the singleton has been instantiated. |
||
313 | */ |
||
314 | public function hasSingleton($class, $checkInstance = false) |
||
315 | { |
||
316 | return $checkInstance ? isset($this->_singletons[$class]) : array_key_exists($class, $this->_singletons); |
||
317 | } |
||
318 | |||
319 | /** |
||
320 | * Removes the definition for the specified name. |
||
321 | * @param string $class class name, interface name or alias name |
||
322 | */ |
||
323 | 2 | public function clear($class) |
|
324 | { |
||
325 | 2 | unset($this->_definitions[$class], $this->_singletons[$class]); |
|
326 | 2 | } |
|
327 | |||
328 | /** |
||
329 | * Normalizes the class definition. |
||
330 | * @param string $class class name |
||
331 | * @param string|array|callable $definition the class definition |
||
332 | * @return array the normalized class definition |
||
333 | * @throws InvalidConfigException if the definition is invalid. |
||
334 | */ |
||
335 | 1053 | protected function normalizeDefinition($class, $definition) |
|
336 | { |
||
337 | 1053 | if (empty($definition)) { |
|
338 | 1 | return ['class' => $class]; |
|
339 | 1053 | } elseif (is_string($definition)) { |
|
340 | 10 | return ['class' => $definition]; |
|
341 | 1049 | } elseif ($definition instanceof Instance) { |
|
342 | 2 | return ['class' => $definition->id]; |
|
343 | 1048 | } elseif (is_callable($definition, true) || is_object($definition)) { |
|
344 | 1020 | return $definition; |
|
345 | 32 | } elseif (is_array($definition)) { |
|
346 | 32 | if (!isset($definition['class']) && isset($definition['__class'])) { |
|
347 | 3 | $definition['class'] = $definition['__class']; |
|
348 | 3 | unset($definition['__class']); |
|
349 | } |
||
350 | 32 | if (!isset($definition['class'])) { |
|
351 | 1 | if (strpos($class, '\\') !== false) { |
|
352 | 1 | $definition['class'] = $class; |
|
353 | } else { |
||
354 | throw new InvalidConfigException('A class definition requires a "class" member.'); |
||
355 | } |
||
356 | } |
||
357 | |||
358 | 32 | return $definition; |
|
359 | } |
||
360 | |||
361 | throw new InvalidConfigException("Unsupported definition type for \"$class\": " . gettype($definition)); |
||
362 | } |
||
363 | |||
364 | /** |
||
365 | * Returns the list of the object definitions or the loaded shared objects. |
||
366 | * @return array the list of the object definitions or the loaded shared objects (type or ID => definition or instance). |
||
367 | */ |
||
368 | public function getDefinitions() |
||
369 | { |
||
370 | return $this->_definitions; |
||
371 | } |
||
372 | |||
373 | /** |
||
374 | * Creates an instance of the specified class. |
||
375 | * This method will resolve dependencies of the specified class, instantiate them, and inject |
||
376 | * them into the new instance of the specified class. |
||
377 | * @param string $class the class name |
||
378 | * @param array $params constructor parameters |
||
379 | * @param array $config configurations to be applied to the new instance |
||
380 | * @return object the newly created instance of the specified class |
||
381 | * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
||
382 | */ |
||
383 | 5156 | protected function build($class, $params, $config) |
|
384 | { |
||
385 | /* @var $reflection ReflectionClass */ |
||
386 | 5156 | list($reflection, $dependencies) = $this->getDependencies($class); |
|
387 | |||
388 | 5151 | $addDependencies = []; |
|
389 | 5151 | if (isset($config['__construct()'])) { |
|
390 | 4 | $addDependencies = $config['__construct()']; |
|
391 | 4 | unset($config['__construct()']); |
|
392 | } |
||
393 | 5151 | foreach ($params as $index => $param) { |
|
394 | 703 | $addDependencies[$index] = $param; |
|
395 | } |
||
396 | |||
397 | 5151 | $this->validateDependencies($addDependencies); |
|
398 | |||
399 | 5150 | if ($addDependencies && is_int(key($addDependencies))) { |
|
400 | 705 | $dependencies = array_values($dependencies); |
|
401 | 705 | $dependencies = $this->mergeDependencies($dependencies, $addDependencies); |
|
402 | } else { |
||
403 | 5150 | $dependencies = $this->mergeDependencies($dependencies, $addDependencies); |
|
404 | 5150 | $dependencies = array_values($dependencies); |
|
405 | } |
||
406 | |||
407 | 5150 | $dependencies = $this->resolveDependencies($dependencies, $reflection); |
|
408 | 5150 | if (!$reflection->isInstantiable()) { |
|
409 | 4 | throw new NotInstantiableException($reflection->name); |
|
410 | } |
||
411 | 5148 | if (empty($config)) { |
|
412 | 2937 | return $reflection->newInstanceArgs($dependencies); |
|
413 | } |
||
414 | |||
415 | 4987 | $config = $this->resolveDependencies($config); |
|
416 | |||
417 | 4987 | if (!empty($dependencies) && $reflection->implementsInterface('yii\base\Configurable')) { |
|
418 | // set $config as the last parameter (existing one will be overwritten) |
||
419 | 4986 | $dependencies[count($dependencies) - 1] = $config; |
|
420 | 4986 | return $reflection->newInstanceArgs($dependencies); |
|
421 | } |
||
422 | |||
423 | 1 | $object = $reflection->newInstanceArgs($dependencies); |
|
424 | 1 | foreach ($config as $name => $value) { |
|
425 | 1 | $object->$name = $value; |
|
426 | } |
||
427 | |||
428 | 1 | return $object; |
|
429 | } |
||
430 | |||
431 | /** |
||
432 | * @param array $a |
||
433 | * @param array $b |
||
434 | * @return array |
||
435 | */ |
||
436 | 5150 | private function mergeDependencies($a, $b) |
|
437 | { |
||
438 | 5150 | foreach ($b as $index => $dependency) { |
|
439 | 706 | $a[$index] = $dependency; |
|
440 | } |
||
441 | 5150 | return $a; |
|
442 | } |
||
443 | |||
444 | /** |
||
445 | * @param array $parameters |
||
446 | * @throws InvalidConfigException |
||
447 | */ |
||
448 | 5151 | private function validateDependencies($parameters) |
|
449 | { |
||
450 | 5151 | $hasStringParameter = false; |
|
451 | 5151 | $hasIntParameter = false; |
|
452 | 5151 | foreach ($parameters as $index => $parameter) { |
|
453 | 707 | if (is_string($index)) { |
|
454 | 2 | $hasStringParameter = true; |
|
455 | 2 | if ($hasIntParameter) { |
|
456 | 2 | break; |
|
457 | } |
||
458 | } else { |
||
459 | 706 | $hasIntParameter = true; |
|
460 | 706 | if ($hasStringParameter) { |
|
461 | 707 | break; |
|
462 | } |
||
463 | } |
||
464 | } |
||
465 | 5151 | if ($hasIntParameter && $hasStringParameter) { |
|
466 | 1 | throw new InvalidConfigException( |
|
467 | 1 | 'Dependencies indexed by name and by position in the same array are not allowed.' |
|
468 | ); |
||
469 | } |
||
470 | 5150 | } |
|
471 | |||
472 | /** |
||
473 | * Merges the user-specified constructor parameters with the ones registered via [[set()]]. |
||
474 | * @param string $class class name, interface name or alias name |
||
475 | * @param array $params the constructor parameters |
||
476 | * @return array the merged parameters |
||
477 | */ |
||
478 | 36 | protected function mergeParams($class, $params) |
|
479 | { |
||
480 | 36 | if (empty($this->_params[$class])) { |
|
481 | 36 | return $params; |
|
482 | } elseif (empty($params)) { |
||
483 | 3 | return $this->_params[$class]; |
|
484 | } |
||
485 | |||
486 | $ps = $this->_params[$class]; |
||
487 | foreach ($params as $index => $value) { |
||
488 | $ps[$index] = $value; |
||
489 | } |
||
490 | |||
491 | return $ps; |
||
492 | } |
||
493 | |||
494 | /** |
||
495 | * Returns the dependencies of the specified class. |
||
496 | * @param string $class class name, interface name or alias name |
||
497 | * @return array the dependencies of the specified class. |
||
498 | * @throws NotInstantiableException if a dependency cannot be resolved or if a dependency cannot be fulfilled. |
||
499 | */ |
||
500 | 5156 | protected function getDependencies($class) |
|
501 | { |
||
502 | 5156 | if (isset($this->_reflections[$class])) { |
|
503 | 5108 | return [$this->_reflections[$class], $this->_dependencies[$class]]; |
|
504 | } |
||
505 | |||
506 | 225 | $dependencies = []; |
|
507 | try { |
||
508 | 225 | $reflection = new ReflectionClass($class); |
|
509 | 5 | } catch (\ReflectionException $e) { |
|
510 | 5 | throw new NotInstantiableException( |
|
511 | 5 | $class, |
|
512 | 5 | 'Failed to instantiate component or class "' . $class . '".', |
|
513 | 5 | 0, |
|
514 | 5 | $e |
|
515 | ); |
||
516 | } |
||
517 | |||
518 | 221 | $constructor = $reflection->getConstructor(); |
|
519 | 221 | if ($constructor !== null) { |
|
520 | 219 | foreach ($constructor->getParameters() as $param) { |
|
521 | 219 | if (PHP_VERSION_ID >= 50600 && $param->isVariadic()) { |
|
522 | 1 | break; |
|
523 | } |
||
524 | |||
525 | 218 | if (PHP_VERSION_ID >= 80000) { |
|
526 | $c = $param->getType(); |
||
527 | $isClass = false; |
||
528 | if ($c instanceof ReflectionNamedType) { |
||
529 | $isClass = !$c->isBuiltin(); |
||
530 | } |
||
531 | } else { |
||
532 | try { |
||
533 | 218 | $c = $param->getClass(); |
|
534 | 3 | } catch (ReflectionException $e) { |
|
535 | 3 | if (!$this->isNulledParam($param)) { |
|
536 | 1 | $notInstantiableClass = null; |
|
537 | 1 | if (PHP_VERSION_ID >= 70000) { |
|
538 | 1 | $type = $param->getType(); |
|
539 | 1 | if ($type instanceof ReflectionNamedType) { |
|
540 | 1 | $notInstantiableClass = $type->getName(); |
|
541 | } |
||
542 | } |
||
543 | 1 | throw new NotInstantiableException( |
|
544 | 1 | $notInstantiableClass, |
|
545 | 1 | $notInstantiableClass === null ? 'Can not instantiate unknown class.' : null |
|
546 | ); |
||
547 | } else { |
||
548 | 2 | $c = null; |
|
549 | } |
||
550 | } |
||
551 | 217 | $isClass = $c !== null; |
|
552 | } |
||
553 | 217 | $className = $isClass ? $c->getName() : null; |
|
554 | |||
555 | 217 | if ($className !== null) { |
|
556 | 7 | $dependencies[$param->getName()] = Instance::of($className, $this->isNulledParam($param)); |
|
557 | } else { |
||
558 | 217 | $dependencies[$param->getName()] = $param->isDefaultValueAvailable() |
|
559 | 215 | ? $param->getDefaultValue() |
|
560 | 217 | : null; |
|
561 | } |
||
562 | } |
||
563 | } |
||
564 | |||
565 | 220 | $this->_reflections[$class] = $reflection; |
|
566 | 220 | $this->_dependencies[$class] = $dependencies; |
|
567 | |||
568 | 220 | return [$reflection, $dependencies]; |
|
569 | } |
||
570 | |||
571 | /** |
||
572 | * @param ReflectionParameter $param |
||
573 | * @return bool |
||
574 | */ |
||
575 | 8 | private function isNulledParam($param) |
|
576 | { |
||
577 | 8 | return $param->isOptional() || (PHP_VERSION_ID >= 70100 && $param->getType()->allowsNull()); |
|
578 | } |
||
579 | |||
580 | /** |
||
581 | * Resolves dependencies by replacing them with the actual object instances. |
||
582 | * @param array $dependencies the dependencies |
||
583 | * @param ReflectionClass $reflection the class reflection associated with the dependencies |
||
584 | * @return array the resolved dependencies |
||
585 | * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled. |
||
586 | */ |
||
587 | 5151 | protected function resolveDependencies($dependencies, $reflection = null) |
|
588 | { |
||
589 | 5151 | foreach ($dependencies as $index => $dependency) { |
|
590 | 5148 | if ($dependency instanceof Instance) { |
|
591 | 8 | if ($dependency->id !== null) { |
|
592 | 8 | $dependencies[$index] = $dependency->get($this); |
|
593 | } elseif ($reflection !== null) { |
||
594 | $name = $reflection->getConstructor()->getParameters()[$index]->getName(); |
||
595 | $class = $reflection->getName(); |
||
596 | 7 | throw new InvalidConfigException("Missing required parameter \"$name\" when instantiating \"$class\"."); |
|
597 | } |
||
598 | 5147 | } elseif ($this->_resolveArrays && is_array($dependency)) { |
|
599 | 5147 | $dependencies[$index] = $this->resolveDependencies($dependency, $reflection); |
|
600 | } |
||
601 | } |
||
602 | |||
603 | 5151 | return $dependencies; |
|
604 | } |
||
605 | |||
606 | /** |
||
607 | * Invoke a callback with resolving dependencies in parameters. |
||
608 | * |
||
609 | * This methods allows invoking a callback and let type hinted parameter names to be |
||
610 | * resolved as objects of the Container. It additionally allow calling function using named parameters. |
||
611 | * |
||
612 | * For example, the following callback may be invoked using the Container to resolve the formatter dependency: |
||
613 | * |
||
614 | * ```php |
||
615 | * $formatString = function($string, \yii\i18n\Formatter $formatter) { |
||
616 | * // ... |
||
617 | * } |
||
618 | * Yii::$container->invoke($formatString, ['string' => 'Hello World!']); |
||
619 | * ``` |
||
620 | * |
||
621 | * This will pass the string `'Hello World!'` as the first param, and a formatter instance created |
||
622 | * by the DI container as the second param to the callable. |
||
623 | * |
||
624 | * @param callable $callback callable to be invoked. |
||
625 | * @param array $params The array of parameters for the function. |
||
626 | * This can be either a list of parameters, or an associative array representing named function parameters. |
||
627 | * @return mixed the callback return value. |
||
628 | * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled. |
||
629 | * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
||
630 | * @since 2.0.7 |
||
631 | */ |
||
632 | 10 | public function invoke(callable $callback, $params = []) |
|
633 | { |
||
634 | 10 | return call_user_func_array($callback, $this->resolveCallableDependencies($callback, $params)); |
|
635 | } |
||
636 | |||
637 | /** |
||
638 | * Resolve dependencies for a function. |
||
639 | * |
||
640 | * This method can be used to implement similar functionality as provided by [[invoke()]] in other |
||
641 | * components. |
||
642 | * |
||
643 | * @param callable $callback callable to be invoked. |
||
644 | * @param array $params The array of parameters for the function, can be either numeric or associative. |
||
645 | * @return array The resolved dependencies. |
||
646 | * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled. |
||
647 | * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
||
648 | * @since 2.0.7 |
||
649 | */ |
||
650 | 11 | public function resolveCallableDependencies(callable $callback, $params = []) |
|
651 | { |
||
652 | 11 | if (is_array($callback)) { |
|
653 | 2 | $reflection = new \ReflectionMethod($callback[0], $callback[1]); |
|
654 | 11 | } elseif (is_object($callback) && !$callback instanceof \Closure) { |
|
655 | 1 | $reflection = new \ReflectionMethod($callback, '__invoke'); |
|
656 | } else { |
||
657 | 11 | $reflection = new \ReflectionFunction($callback); |
|
658 | } |
||
659 | |||
660 | 11 | $args = []; |
|
661 | |||
662 | 11 | $associative = ArrayHelper::isAssociative($params); |
|
663 | |||
664 | 11 | foreach ($reflection->getParameters() as $param) { |
|
665 | 6 | $name = $param->getName(); |
|
666 | |||
667 | 6 | if (PHP_VERSION_ID >= 80000) { |
|
668 | $class = $param->getType(); |
||
669 | $isClass = $class !== null && !$param->getType()->isBuiltin(); |
||
670 | } else { |
||
671 | 6 | $class = $param->getClass(); |
|
672 | 6 | $isClass = $class !== null; |
|
673 | } |
||
674 | |||
675 | 6 | if ($isClass) { |
|
676 | 4 | $className = $class->getName(); |
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
677 | 4 | if (PHP_VERSION_ID >= 50600 && $param->isVariadic()) { |
|
678 | 1 | $args = array_merge($args, array_values($params)); |
|
679 | 1 | break; |
|
680 | } |
||
681 | |||
682 | 3 | if ($associative && isset($params[$name]) && $params[$name] instanceof $className) { |
|
683 | $args[] = $params[$name]; |
||
684 | unset($params[$name]); |
||
685 | 3 | } elseif (!$associative && isset($params[0]) && $params[0] instanceof $className) { |
|
686 | 1 | $args[] = array_shift($params); |
|
687 | 3 | } elseif (isset(Yii::$app) && Yii::$app->has($name) && ($obj = Yii::$app->get($name)) instanceof $className) { |
|
688 | 1 | $args[] = $obj; |
|
689 | } else { |
||
690 | // If the argument is optional we catch not instantiable exceptions |
||
691 | try { |
||
692 | 3 | $args[] = $this->get($className); |
|
693 | 1 | } catch (NotInstantiableException $e) { |
|
694 | 1 | if ($param->isDefaultValueAvailable()) { |
|
695 | 1 | $args[] = $param->getDefaultValue(); |
|
696 | } else { |
||
697 | 3 | throw $e; |
|
698 | } |
||
699 | } |
||
700 | } |
||
701 | 4 | } elseif ($associative && isset($params[$name])) { |
|
702 | 2 | $args[] = $params[$name]; |
|
703 | 2 | unset($params[$name]); |
|
704 | 4 | } elseif (!$associative && count($params)) { |
|
705 | 3 | $args[] = array_shift($params); |
|
706 | 3 | } elseif ($param->isDefaultValueAvailable()) { |
|
707 | 3 | $args[] = $param->getDefaultValue(); |
|
708 | 1 | } elseif (!$param->isOptional()) { |
|
709 | $funcName = $reflection->getName(); |
||
710 | 5 | throw new InvalidConfigException("Missing required parameter \"$name\" when calling \"$funcName\"."); |
|
711 | } |
||
712 | } |
||
713 | |||
714 | 11 | foreach ($params as $value) { |
|
715 | $args[] = $value; |
||
716 | } |
||
717 | |||
718 | 11 | return $args; |
|
719 | } |
||
720 | |||
721 | /** |
||
722 | * Registers class definitions within this container. |
||
723 | * |
||
724 | * @param array $definitions array of definitions. There are two allowed formats of array. |
||
725 | * The first format: |
||
726 | * - key: class name, interface name or alias name. The key will be passed to the [[set()]] method |
||
727 | * as a first argument `$class`. |
||
728 | * - value: the definition associated with `$class`. Possible values are described in |
||
729 | * [[set()]] documentation for the `$definition` parameter. Will be passed to the [[set()]] method |
||
730 | * as the second argument `$definition`. |
||
731 | * |
||
732 | * Example: |
||
733 | * ```php |
||
734 | * $container->setDefinitions([ |
||
735 | * 'yii\web\Request' => 'app\components\Request', |
||
736 | * 'yii\web\Response' => [ |
||
737 | * 'class' => 'app\components\Response', |
||
738 | * 'format' => 'json' |
||
739 | * ], |
||
740 | * 'foo\Bar' => function () { |
||
741 | * $qux = new Qux; |
||
742 | * $foo = new Foo($qux); |
||
743 | * return new Bar($foo); |
||
744 | * } |
||
745 | * ]); |
||
746 | * ``` |
||
747 | * |
||
748 | * The second format: |
||
749 | * - key: class name, interface name or alias name. The key will be passed to the [[set()]] method |
||
750 | * as a first argument `$class`. |
||
751 | * - value: array of two elements. The first element will be passed the [[set()]] method as the |
||
752 | * second argument `$definition`, the second one — as `$params`. |
||
753 | * |
||
754 | * Example: |
||
755 | * ```php |
||
756 | * $container->setDefinitions([ |
||
757 | * 'foo\Bar' => [ |
||
758 | * ['class' => 'app\Bar'], |
||
759 | * [Instance::of('baz')] |
||
760 | * ] |
||
761 | * ]); |
||
762 | * ``` |
||
763 | * |
||
764 | * @see set() to know more about possible values of definitions |
||
765 | * @since 2.0.11 |
||
766 | */ |
||
767 | 8 | public function setDefinitions(array $definitions) |
|
768 | { |
||
769 | 8 | foreach ($definitions as $class => $definition) { |
|
770 | 8 | if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition && is_array($definition[1])) { |
|
771 | 1 | $this->set($class, $definition[0], $definition[1]); |
|
772 | 1 | continue; |
|
773 | } |
||
774 | |||
775 | 8 | $this->set($class, $definition); |
|
776 | } |
||
777 | 8 | } |
|
778 | |||
779 | /** |
||
780 | * Registers class definitions as singletons within this container by calling [[setSingleton()]]. |
||
781 | * |
||
782 | * @param array $singletons array of singleton definitions. See [[setDefinitions()]] |
||
783 | * for allowed formats of array. |
||
784 | * |
||
785 | * @see setDefinitions() for allowed formats of $singletons parameter |
||
786 | * @see setSingleton() to know more about possible values of definitions |
||
787 | * @since 2.0.11 |
||
788 | */ |
||
789 | 10 | public function setSingletons(array $singletons) |
|
790 | { |
||
791 | 10 | foreach ($singletons as $class => $definition) { |
|
792 | 10 | if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition) { |
|
793 | 1 | $this->setSingleton($class, $definition[0], $definition[1]); |
|
794 | 1 | continue; |
|
795 | } |
||
796 | |||
797 | 10 | $this->setSingleton($class, $definition); |
|
798 | } |
||
799 | 10 | } |
|
800 | |||
801 | /** |
||
802 | * @param bool $value whether to attempt to resolve elements in array dependencies |
||
803 | * @since 2.0.37 |
||
804 | */ |
||
805 | 1 | public function setResolveArrays($value) |
|
806 | { |
||
807 | 1 | $this->_resolveArrays = (bool) $value; |
|
808 | 1 | } |
|
809 | } |
||
810 |