Passed
Push — add-php8-support ( d66e31 )
by Alexander
11:52
created

Container::getDependencies()   B

Complexity

Conditions 10
Paths 5

Size

Total Lines 35
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 10.0107

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 23
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 35
ccs 20
cts 21
cp 0.9524
crap 10.0107
rs 7.6666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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|Instance $class the class Instance, 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 3716
    public function get($class, $params = [], $config = [])
151
    {
152 3716
        if ($class instanceof Instance) {
153 1
            $class = $class->id;
154
        }
155 3716
        if (isset($this->_singletons[$class])) {
156
            // singleton
157 4
            return $this->_singletons[$class];
158 3716
        } elseif (!isset($this->_definitions[$class])) {
159 3713
            return $this->build($class, $params, $config);
160
        }
161
162 34
        $definition = $this->_definitions[$class];
163
164 34
        if (is_callable($definition, true)) {
165 6
            $params = $this->resolveDependencies($this->mergeParams($class, $params));
166 6
            $object = call_user_func($definition, $this, $params, $config);
167 31
        } elseif (is_array($definition)) {
168 30
            $concrete = $definition['class'];
169 30
            unset($definition['class']);
170
171 30
            $config = array_merge($definition, $config);
172 30
            $params = $this->mergeParams($class, $params);
173
174 30
            if ($concrete === $class) {
175 4
                $object = $this->build($class, $params, $config);
176
            } else {
177 30
                $object = $this->get($concrete, $params, $config);
178
            }
179 2
        } elseif (is_object($definition)) {
180 2
            return $this->_singletons[$class] = $definition;
181
        } else {
182
            throw new InvalidConfigException('Unexpected object definition type: ' . gettype($definition));
183
        }
184
185 31
        if (array_key_exists($class, $this->_singletons)) {
186
            // singleton
187 5
            $this->_singletons[$class] = $object;
188
        }
189
190 31
        return $object;
191
    }
192
193
    /**
194
     * Registers a class definition with this container.
195
     *
196
     * For example,
197
     *
198
     * ```php
199
     * // register a class name as is. This can be skipped.
200
     * $container->set('yii\db\Connection');
201
     *
202
     * // register an interface
203
     * // When a class depends on the interface, the corresponding class
204
     * // will be instantiated as the dependent object
205
     * $container->set('yii\mail\MailInterface', 'yii\swiftmailer\Mailer');
206
     *
207
     * // register an alias name. You can use $container->get('foo')
208
     * // to create an instance of Connection
209
     * $container->set('foo', 'yii\db\Connection');
210
     *
211
     * // register a class with configuration. The configuration
212
     * // will be applied when the class is instantiated by get()
213
     * $container->set('yii\db\Connection', [
214
     *     'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
215
     *     'username' => 'root',
216
     *     'password' => '',
217
     *     'charset' => 'utf8',
218
     * ]);
219
     *
220
     * // register an alias name with class configuration
221
     * // In this case, a "class" element is required to specify the class
222
     * $container->set('db', [
223
     *     'class' => 'yii\db\Connection',
224
     *     'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
225
     *     'username' => 'root',
226
     *     'password' => '',
227
     *     'charset' => 'utf8',
228
     * ]);
229
     *
230
     * // register a PHP callable
231
     * // The callable will be executed when $container->get('db') is called
232
     * $container->set('db', function ($container, $params, $config) {
233
     *     return new \yii\db\Connection($config);
234
     * });
235
     * ```
236
     *
237
     * If a class definition with the same name already exists, it will be overwritten with the new one.
238
     * You may use [[has()]] to check if a class definition already exists.
239
     *
240
     * @param string $class class name, interface name or alias name
241
     * @param mixed $definition the definition associated with `$class`. It can be one of the following:
242
     *
243
     * - a PHP callable: The callable will be executed when [[get()]] is invoked. The signature of the callable
244
     *   should be `function ($container, $params, $config)`, where `$params` stands for the list of constructor
245
     *   parameters, `$config` the object configuration, and `$container` the container object. The return value
246
     *   of the callable will be returned by [[get()]] as the object instance requested.
247
     * - a configuration array: the array contains name-value pairs that will be used to initialize the property
248
     *   values of the newly created object when [[get()]] is called. The `class` element stands for the
249
     *   the class of the object to be created. If `class` is not specified, `$class` will be used as the class name.
250
     * - a string: a class name, an interface name or an alias name.
251
     * @param array $params the list of constructor parameters. The parameters will be passed to the class
252
     * constructor when [[get()]] is called.
253
     * @return $this the container itself
254
     */
255 636
    public function set($class, $definition = [], array $params = [])
256
    {
257 636
        $this->_definitions[$class] = $this->normalizeDefinition($class, $definition);
258 636
        $this->_params[$class] = $params;
259 636
        unset($this->_singletons[$class]);
260 636
        return $this;
261
    }
262
263
    /**
264
     * Registers a class definition with this container and marks the class as a singleton class.
265
     *
266
     * This method is similar to [[set()]] except that classes registered via this method will only have one
267
     * instance. Each time [[get()]] is called, the same instance of the specified class will be returned.
268
     *
269
     * @param string $class class name, interface name or alias name
270
     * @param mixed $definition the definition associated with `$class`. See [[set()]] for more details.
271
     * @param array $params the list of constructor parameters. The parameters will be passed to the class
272
     * constructor when [[get()]] is called.
273
     * @return $this the container itself
274
     * @see set()
275
     */
276 10
    public function setSingleton($class, $definition = [], array $params = [])
277
    {
278 10
        $this->_definitions[$class] = $this->normalizeDefinition($class, $definition);
279 10
        $this->_params[$class] = $params;
280 10
        $this->_singletons[$class] = null;
281 10
        return $this;
282
    }
283
284
    /**
285
     * Returns a value indicating whether the container has the definition of the specified name.
286
     * @param string $class class name, interface name or alias name
287
     * @return bool whether the container has the definition of the specified name..
288
     * @see set()
289
     */
290 8
    public function has($class)
291
    {
292 8
        return isset($this->_definitions[$class]);
293
    }
294
295
    /**
296
     * Returns a value indicating whether the given name corresponds to a registered singleton.
297
     * @param string $class class name, interface name or alias name
298
     * @param bool $checkInstance whether to check if the singleton has been instantiated.
299
     * @return bool whether the given name corresponds to a registered singleton. If `$checkInstance` is true,
300
     * the method should return a value indicating whether the singleton has been instantiated.
301
     */
302
    public function hasSingleton($class, $checkInstance = false)
303
    {
304
        return $checkInstance ? isset($this->_singletons[$class]) : array_key_exists($class, $this->_singletons);
305
    }
306
307
    /**
308
     * Removes the definition for the specified name.
309
     * @param string $class class name, interface name or alias name
310
     */
311 2
    public function clear($class)
312
    {
313 2
        unset($this->_definitions[$class], $this->_singletons[$class]);
314 2
    }
315
316
    /**
317
     * Normalizes the class definition.
318
     * @param string $class class name
319
     * @param string|array|callable $definition the class definition
320
     * @return array the normalized class definition
321
     * @throws InvalidConfigException if the definition is invalid.
322
     */
323 646
    protected function normalizeDefinition($class, $definition)
324
    {
325 646
        if (empty($definition)) {
326 1
            return ['class' => $class];
327 646
        } elseif (is_string($definition)) {
328 8
            return ['class' => $definition];
329 643
        } elseif ($definition instanceof Instance) {
330 2
            return ['class' => $definition->id];
331 642
        } elseif (is_callable($definition, true) || is_object($definition)) {
332 614
            return $definition;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $definition also could return the type callable which is incompatible with the documented return type array.
Loading history...
333 31
        } elseif (is_array($definition)) {
334 31
            if (!isset($definition['class']) && isset($definition['__class'])) {
335 3
                $definition['class'] = $definition['__class'];
336 3
                unset($definition['__class']);
337
            }
338 31
            if (!isset($definition['class'])) {
339 1
                if (strpos($class, '\\') !== false) {
340 1
                    $definition['class'] = $class;
341
                } else {
342
                    throw new InvalidConfigException('A class definition requires a "class" member.');
343
                }
344
            }
345
346 31
            return $definition;
347
        }
348
349
        throw new InvalidConfigException("Unsupported definition type for \"$class\": " . gettype($definition));
350
    }
351
352
    /**
353
     * Returns the list of the object definitions or the loaded shared objects.
354
     * @return array the list of the object definitions or the loaded shared objects (type or ID => definition or instance).
355
     */
356
    public function getDefinitions()
357
    {
358
        return $this->_definitions;
359
    }
360
361
    /**
362
     * Creates an instance of the specified class.
363
     * This method will resolve dependencies of the specified class, instantiate them, and inject
364
     * them into the new instance of the specified class.
365
     * @param string $class the class name
366
     * @param array $params constructor parameters
367
     * @param array $config configurations to be applied to the new instance
368
     * @return object the newly created instance of the specified class
369
     * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
370
     */
371 3714
    protected function build($class, $params, $config)
372
    {
373
        /* @var $reflection ReflectionClass */
374 3714
        list($reflection, $dependencies) = $this->getDependencies($class);
375
376 3710
        if (isset($config['__construct()'])) {
377 3
            foreach ($config['__construct()'] as $index => $param) {
378 3
                $dependencies[$index] = $param;
379
            }
380 3
            unset($config['__construct()']);
381
        }
382
383 3710
        foreach ($params as $index => $param) {
384 478
            $dependencies[$index] = $param;
385
        }
386
387 3710
        $dependencies = $this->resolveDependencies($dependencies, $reflection);
388 3710
        if (!$reflection->isInstantiable()) {
389 1
            throw new NotInstantiableException($reflection->name);
390
        }
391 3709
        if (empty($config)) {
392 2298
            return $reflection->newInstanceArgs($dependencies);
393
        }
394
395 3553
        $config = $this->resolveDependencies($config);
396
397 3553
        if (!empty($dependencies) && $reflection->implementsInterface('yii\base\Configurable')) {
398
            // set $config as the last parameter (existing one will be overwritten)
399 3552
            $dependencies[count($dependencies) - 1] = $config;
400 3552
            return $reflection->newInstanceArgs($dependencies);
401
        }
402
403 1
        $object = $reflection->newInstanceArgs($dependencies);
404 1
        foreach ($config as $name => $value) {
405 1
            $object->$name = $value;
406
        }
407
408 1
        return $object;
409
    }
410
411
    /**
412
     * Merges the user-specified constructor parameters with the ones registered via [[set()]].
413
     * @param string $class class name, interface name or alias name
414
     * @param array $params the constructor parameters
415
     * @return array the merged parameters
416
     */
417 33
    protected function mergeParams($class, $params)
418
    {
419 33
        if (empty($this->_params[$class])) {
420 33
            return $params;
421
        } elseif (empty($params)) {
422 3
            return $this->_params[$class];
423
        }
424
425
        $ps = $this->_params[$class];
426
        foreach ($params as $index => $value) {
427
            $ps[$index] = $value;
428
        }
429
430
        return $ps;
431
    }
432
433
    /**
434
     * Returns the dependencies of the specified class.
435
     * @param string $class class name, interface name or alias name
436
     * @return array the dependencies of the specified class.
437
     * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
438
     */
439 3714
    protected function getDependencies($class)
440
    {
441 3714
        if (isset($this->_reflections[$class])) {
442 3674
            return [$this->_reflections[$class], $this->_dependencies[$class]];
443
        }
444
445 183
        $dependencies = [];
446
        try {
447 183
            $reflection = new ReflectionClass($class);
448 5
        } catch (\ReflectionException $e) {
449 5
            throw new InvalidConfigException('Failed to instantiate component or class "' . $class . '".', 0, $e);
450
        }
451
452 179
        $constructor = $reflection->getConstructor();
453 179
        if ($constructor !== null) {
454 177
            foreach ($constructor->getParameters() as $param) {
455 177
                if (version_compare(PHP_VERSION, '5.6.0', '>=') && $param->isVariadic()) {
456 1
                    break;
457 176
                } elseif ($param->isDefaultValueAvailable()) {
458 176
                    $dependencies[] = $param->getDefaultValue();
459
                } else {
460 24
                    if (PHP_VERSION_ID >= 80000) {
461
                        $c = $param->getType();
462
                    } else {
463 24
                        $c = $param->getClass();
464
                    }
465 176
                    $dependencies[] = Instance::of($c === null ? null : $c->getName());
466
                }
467
            }
468
        }
469
470 179
        $this->_reflections[$class] = $reflection;
471 179
        $this->_dependencies[$class] = $dependencies;
472
473 179
        return [$reflection, $dependencies];
474
    }
475
476
    /**
477
     * Resolves dependencies by replacing them with the actual object instances.
478
     * @param array $dependencies the dependencies
479
     * @param ReflectionClass $reflection the class reflection associated with the dependencies
480
     * @return array the resolved dependencies
481
     * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
482
     */
483 3711
    protected function resolveDependencies($dependencies, $reflection = null)
484
    {
485 3711
        foreach ($dependencies as $index => $dependency) {
486 3708
            if ($dependency instanceof Instance) {
487 5
                if ($dependency->id !== null) {
488 5
                    $dependencies[$index] = $this->get($dependency->id);
489
                } elseif ($reflection !== null) {
490
                    $name = $reflection->getConstructor()->getParameters()[$index]->getName();
491
                    $class = $reflection->getName();
492 5
                    throw new InvalidConfigException("Missing required parameter \"$name\" when instantiating \"$class\".");
493
                }
494 3708
            } elseif (is_array($dependency)) {
495 3708
                $dependencies[$index] = $this->resolveDependencies($dependency, $reflection);
496
            }
497
        }
498
499 3711
        return $dependencies;
500
    }
501
502
    /**
503
     * Invoke a callback with resolving dependencies in parameters.
504
     *
505
     * This methods allows invoking a callback and let type hinted parameter names to be
506
     * resolved as objects of the Container. It additionally allow calling function using named parameters.
507
     *
508
     * For example, the following callback may be invoked using the Container to resolve the formatter dependency:
509
     *
510
     * ```php
511
     * $formatString = function($string, \yii\i18n\Formatter $formatter) {
512
     *    // ...
513
     * }
514
     * Yii::$container->invoke($formatString, ['string' => 'Hello World!']);
515
     * ```
516
     *
517
     * This will pass the string `'Hello World!'` as the first param, and a formatter instance created
518
     * by the DI container as the second param to the callable.
519
     *
520
     * @param callable $callback callable to be invoked.
521
     * @param array $params The array of parameters for the function.
522
     * This can be either a list of parameters, or an associative array representing named function parameters.
523
     * @return mixed the callback return value.
524
     * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
525
     * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
526
     * @since 2.0.7
527
     */
528 10
    public function invoke(callable $callback, $params = [])
529
    {
530 10
        return call_user_func_array($callback, $this->resolveCallableDependencies($callback, $params));
531
    }
532
533
    /**
534
     * Resolve dependencies for a function.
535
     *
536
     * This method can be used to implement similar functionality as provided by [[invoke()]] in other
537
     * components.
538
     *
539
     * @param callable $callback callable to be invoked.
540
     * @param array $params The array of parameters for the function, can be either numeric or associative.
541
     * @return array The resolved dependencies.
542
     * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
543
     * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
544
     * @since 2.0.7
545
     */
546 11
    public function resolveCallableDependencies(callable $callback, $params = [])
547
    {
548 11
        if (is_array($callback)) {
549 2
            $reflection = new \ReflectionMethod($callback[0], $callback[1]);
550 11
        } elseif (is_object($callback) && !$callback instanceof \Closure) {
551 1
            $reflection = new \ReflectionMethod($callback, '__invoke');
552
        } else {
553 11
            $reflection = new \ReflectionFunction($callback);
554
        }
555
556 11
        $args = [];
557
558 11
        $associative = ArrayHelper::isAssociative($params);
559
560 11
        foreach ($reflection->getParameters() as $param) {
561 6
            $name = $param->getName();
562 6
            if (($class = $param->getClass()) !== null) {
563 4
                $className = $class->getName();
564 4
                if (version_compare(PHP_VERSION, '5.6.0', '>=') && $param->isVariadic()) {
565 1
                    $args = array_merge($args, array_values($params));
566 1
                    break;
567 3
                } elseif ($associative && isset($params[$name]) && $params[$name] instanceof $className) {
568
                    $args[] = $params[$name];
569
                    unset($params[$name]);
570 3
                } elseif (!$associative && isset($params[0]) && $params[0] instanceof $className) {
571 1
                    $args[] = array_shift($params);
572 3
                } elseif (isset(Yii::$app) && Yii::$app->has($name) && ($obj = Yii::$app->get($name)) instanceof $className) {
573 1
                    $args[] = $obj;
574
                } else {
575
                    // If the argument is optional we catch not instantiable exceptions
576
                    try {
577 3
                        $args[] = $this->get($className);
578 1
                    } catch (NotInstantiableException $e) {
579 1
                        if ($param->isDefaultValueAvailable()) {
580 1
                            $args[] = $param->getDefaultValue();
581
                        } else {
582 3
                            throw $e;
583
                        }
584
                    }
585
                }
586 4
            } elseif ($associative && isset($params[$name])) {
587 2
                $args[] = $params[$name];
588 2
                unset($params[$name]);
589 4
            } elseif (!$associative && count($params)) {
590 3
                $args[] = array_shift($params);
591 3
            } elseif ($param->isDefaultValueAvailable()) {
592 3
                $args[] = $param->getDefaultValue();
593 1
            } elseif (!$param->isOptional()) {
594
                $funcName = $reflection->getName();
595 5
                throw new InvalidConfigException("Missing required parameter \"$name\" when calling \"$funcName\".");
596
            }
597
        }
598
599 11
        foreach ($params as $value) {
600
            $args[] = $value;
601
        }
602
603 11
        return $args;
604
    }
605
606
    /**
607
     * Registers class definitions within this container.
608
     *
609
     * @param array $definitions array of definitions. There are two allowed formats of array.
610
     * The first format:
611
     *  - key: class name, interface name or alias name. The key will be passed to the [[set()]] method
612
     *    as a first argument `$class`.
613
     *  - value: the definition associated with `$class`. Possible values are described in
614
     *    [[set()]] documentation for the `$definition` parameter. Will be passed to the [[set()]] method
615
     *    as the second argument `$definition`.
616
     *
617
     * Example:
618
     * ```php
619
     * $container->setDefinitions([
620
     *     'yii\web\Request' => 'app\components\Request',
621
     *     'yii\web\Response' => [
622
     *         'class' => 'app\components\Response',
623
     *         'format' => 'json'
624
     *     ],
625
     *     'foo\Bar' => function () {
626
     *         $qux = new Qux;
627
     *         $foo = new Foo($qux);
628
     *         return new Bar($foo);
629
     *     }
630
     * ]);
631
     * ```
632
     *
633
     * The second format:
634
     *  - key: class name, interface name or alias name. The key will be passed to the [[set()]] method
635
     *    as a first argument `$class`.
636
     *  - value: array of two elements. The first element will be passed the [[set()]] method as the
637
     *    second argument `$definition`, the second one — as `$params`.
638
     *
639
     * Example:
640
     * ```php
641
     * $container->setDefinitions([
642
     *     'foo\Bar' => [
643
     *          ['class' => 'app\Bar'],
644
     *          [Instance::of('baz')]
645
     *      ]
646
     * ]);
647
     * ```
648
     *
649
     * @see set() to know more about possible values of definitions
650
     * @since 2.0.11
651
     */
652 6
    public function setDefinitions(array $definitions)
653
    {
654 6
        foreach ($definitions as $class => $definition) {
655 6
            if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition && is_array($definition[1])) {
656 1
                $this->set($class, $definition[0], $definition[1]);
657 1
                continue;
658
            }
659
660 6
            $this->set($class, $definition);
661
        }
662 6
    }
663
664
    /**
665
     * Registers class definitions as singletons within this container by calling [[setSingleton()]].
666
     *
667
     * @param array $singletons array of singleton definitions. See [[setDefinitions()]]
668
     * for allowed formats of array.
669
     *
670
     * @see setDefinitions() for allowed formats of $singletons parameter
671
     * @see setSingleton() to know more about possible values of definitions
672
     * @since 2.0.11
673
     */
674 10
    public function setSingletons(array $singletons)
675
    {
676 10
        foreach ($singletons as $class => $definition) {
677 10
            if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition) {
678 1
                $this->setSingleton($class, $definition[0], $definition[1]);
679 1
                continue;
680
            }
681
682 10
            $this->setSingleton($class, $definition);
683
        }
684 10
    }
685
}
686