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