Passed
Push — fix-php8 ( 2b80f5...4b5dda )
by Alexander
10:50 queued 02:12
created

Container   F

Complexity

Total Complexity 99

Size/Duplication

Total Lines 612
Duplicated Lines 0 %

Test Coverage

Coverage 87.96%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 189
c 4
b 0
f 0
dl 0
loc 612
ccs 168
cts 191
cp 0.8796
rs 2
wmc 99

17 Methods

Rating   Name   Duplication   Size   Complexity  
B normalizeDefinition() 0 27 11
A has() 0 3 1
A setSingleton() 0 6 1
A set() 0 6 1
A hasSingleton() 0 3 2
A getDefinitions() 0 3 1
A clear() 0 3 1
B build() 0 38 9
A mergeParams() 0 14 4
B get() 0 41 9
A setSingletons() 0 9 5
B getDependencies() 0 39 11
B resolveDependencies() 0 17 7
A invoke() 0 3 1
A setDefinitions() 0 9 6
D resolveCallableDependencies() 0 69 28
A setResolveArrays() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like Container often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Container, and based on these observations, apply Extract Interface, too.

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