Passed
Push — fix-php8 ( d5fd52...924a16 )
by Alexander
10:49 queued 01:32
created

Container   F

Complexity

Total Complexity 97

Size/Duplication

Total Lines 607
Duplicated Lines 0 %

Test Coverage

Coverage 88.77%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 185
c 3
b 0
f 0
dl 0
loc 607
ccs 166
cts 187
cp 0.8877
rs 2
wmc 97

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 37 10
B resolveDependencies() 0 17 7
A invoke() 0 3 1
A setDefinitions() 0 9 6
D resolveCallableDependencies() 0 66 27
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
                    } else {
471 25
                        $c = $param->getClass();
472
                    }
473 178
                    $dependencies[] = Instance::of($c === null ? null : $c->getName());
474
                }
475
            }
476
        }
477
478 181
        $this->_reflections[$class] = $reflection;
479 181
        $this->_dependencies[$class] = $dependencies;
480
481 181
        return [$reflection, $dependencies];
482
    }
483
484
    /**
485
     * Resolves dependencies by replacing them with the actual object instances.
486
     * @param array $dependencies the dependencies
487
     * @param ReflectionClass $reflection the class reflection associated with the dependencies
488
     * @return array the resolved dependencies
489
     * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
490
     */
491 3777
    protected function resolveDependencies($dependencies, $reflection = null)
492
    {
493 3777
        foreach ($dependencies as $index => $dependency) {
494 3774
            if ($dependency instanceof Instance) {
495 5
                if ($dependency->id !== null) {
496 5
                    $dependencies[$index] = $this->get($dependency->id);
497
                } elseif ($reflection !== null) {
498
                    $name = $reflection->getConstructor()->getParameters()[$index]->getName();
499
                    $class = $reflection->getName();
500 5
                    throw new InvalidConfigException("Missing required parameter \"$name\" when instantiating \"$class\".");
501
                }
502 3774
            } elseif ($this->_resolveArrays && is_array($dependency)) {
503 3774
                $dependencies[$index] = $this->resolveDependencies($dependency, $reflection);
504
            }
505
        }
506
507 3777
        return $dependencies;
508
    }
509
510
    /**
511
     * Invoke a callback with resolving dependencies in parameters.
512
     *
513
     * This methods allows invoking a callback and let type hinted parameter names to be
514
     * resolved as objects of the Container. It additionally allow calling function using named parameters.
515
     *
516
     * For example, the following callback may be invoked using the Container to resolve the formatter dependency:
517
     *
518
     * ```php
519
     * $formatString = function($string, \yii\i18n\Formatter $formatter) {
520
     *    // ...
521
     * }
522
     * Yii::$container->invoke($formatString, ['string' => 'Hello World!']);
523
     * ```
524
     *
525
     * This will pass the string `'Hello World!'` as the first param, and a formatter instance created
526
     * by the DI container as the second param to the callable.
527
     *
528
     * @param callable $callback callable to be invoked.
529
     * @param array $params The array of parameters for the function.
530
     * This can be either a list of parameters, or an associative array representing named function parameters.
531
     * @return mixed the callback return value.
532
     * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
533
     * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
534
     * @since 2.0.7
535
     */
536 10
    public function invoke(callable $callback, $params = [])
537
    {
538 10
        return call_user_func_array($callback, $this->resolveCallableDependencies($callback, $params));
539
    }
540
541
    /**
542
     * Resolve dependencies for a function.
543
     *
544
     * This method can be used to implement similar functionality as provided by [[invoke()]] in other
545
     * components.
546
     *
547
     * @param callable $callback callable to be invoked.
548
     * @param array $params The array of parameters for the function, can be either numeric or associative.
549
     * @return array The resolved dependencies.
550
     * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
551
     * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
552
     * @since 2.0.7
553
     */
554 11
    public function resolveCallableDependencies(callable $callback, $params = [])
555
    {
556 11
        if (is_array($callback)) {
557 2
            $reflection = new \ReflectionMethod($callback[0], $callback[1]);
558 11
        } elseif (is_object($callback) && !$callback instanceof \Closure) {
559 1
            $reflection = new \ReflectionMethod($callback, '__invoke');
560
        } else {
561 11
            $reflection = new \ReflectionFunction($callback);
562
        }
563
564 11
        $args = [];
565
566 11
        $associative = ArrayHelper::isAssociative($params);
567
568 11
        foreach ($reflection->getParameters() as $param) {
569 6
            $name = $param->getName();
570 6
            if (PHP_VERSION_ID >= 80000) {
571
                $class = $param->getType();
572
            } else {
573 6
                $class = $param->getClass();
574
            }
575
576 6
            if ($class !== null) {
577 4
                $className = $class->getName();
578 4
                if (PHP_VERSION_ID >= 50600 && $param->isVariadic()) {
579 1
                    $args = array_merge($args, array_values($params));
580 1
                    break;
581
                }
582
583 3
                if ($associative && isset($params[$name]) && $params[$name] instanceof $className) {
584
                    $args[] = $params[$name];
585
                    unset($params[$name]);
586 3
                } elseif (!$associative && isset($params[0]) && $params[0] instanceof $className) {
587 1
                    $args[] = array_shift($params);
588 3
                } elseif (isset(Yii::$app) && Yii::$app->has($name) && ($obj = Yii::$app->get($name)) instanceof $className) {
589 1
                    $args[] = $obj;
590
                } else {
591
                    // If the argument is optional we catch not instantiable exceptions
592
                    try {
593 3
                        $args[] = $this->get($className);
594 1
                    } catch (NotInstantiableException $e) {
595 1
                        if ($param->isDefaultValueAvailable()) {
596 1
                            $args[] = $param->getDefaultValue();
597
                        } else {
598 3
                            throw $e;
599
                        }
600
                    }
601
                }
602 4
            } elseif ($associative && isset($params[$name])) {
603 2
                $args[] = $params[$name];
604 2
                unset($params[$name]);
605 4
            } elseif (!$associative && count($params)) {
606 3
                $args[] = array_shift($params);
607 3
            } elseif ($param->isDefaultValueAvailable()) {
608 3
                $args[] = $param->getDefaultValue();
609 1
            } elseif (!$param->isOptional()) {
610
                $funcName = $reflection->getName();
611 5
                throw new InvalidConfigException("Missing required parameter \"$name\" when calling \"$funcName\".");
612
            }
613
        }
614
615 11
        foreach ($params as $value) {
616
            $args[] = $value;
617
        }
618
619 11
        return $args;
620
    }
621
622
    /**
623
     * Registers class definitions within this container.
624
     *
625
     * @param array $definitions array of definitions. There are two allowed formats of array.
626
     * The first format:
627
     *  - key: class name, interface name or alias name. The key will be passed to the [[set()]] method
628
     *    as a first argument `$class`.
629
     *  - value: the definition associated with `$class`. Possible values are described in
630
     *    [[set()]] documentation for the `$definition` parameter. Will be passed to the [[set()]] method
631
     *    as the second argument `$definition`.
632
     *
633
     * Example:
634
     * ```php
635
     * $container->setDefinitions([
636
     *     'yii\web\Request' => 'app\components\Request',
637
     *     'yii\web\Response' => [
638
     *         'class' => 'app\components\Response',
639
     *         'format' => 'json'
640
     *     ],
641
     *     'foo\Bar' => function () {
642
     *         $qux = new Qux;
643
     *         $foo = new Foo($qux);
644
     *         return new Bar($foo);
645
     *     }
646
     * ]);
647
     * ```
648
     *
649
     * The second format:
650
     *  - key: class name, interface name or alias name. The key will be passed to the [[set()]] method
651
     *    as a first argument `$class`.
652
     *  - value: array of two elements. The first element will be passed the [[set()]] method as the
653
     *    second argument `$definition`, the second one — as `$params`.
654
     *
655
     * Example:
656
     * ```php
657
     * $container->setDefinitions([
658
     *     'foo\Bar' => [
659
     *          ['class' => 'app\Bar'],
660
     *          [Instance::of('baz')]
661
     *      ]
662
     * ]);
663
     * ```
664
     *
665
     * @see set() to know more about possible values of definitions
666
     * @since 2.0.11
667
     */
668 7
    public function setDefinitions(array $definitions)
669
    {
670 7
        foreach ($definitions as $class => $definition) {
671 7
            if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition && is_array($definition[1])) {
672 1
                $this->set($class, $definition[0], $definition[1]);
673 1
                continue;
674
            }
675
676 7
            $this->set($class, $definition);
677
        }
678 7
    }
679
680
    /**
681
     * Registers class definitions as singletons within this container by calling [[setSingleton()]].
682
     *
683
     * @param array $singletons array of singleton definitions. See [[setDefinitions()]]
684
     * for allowed formats of array.
685
     *
686
     * @see setDefinitions() for allowed formats of $singletons parameter
687
     * @see setSingleton() to know more about possible values of definitions
688
     * @since 2.0.11
689
     */
690 10
    public function setSingletons(array $singletons)
691
    {
692 10
        foreach ($singletons as $class => $definition) {
693 10
            if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition) {
694 1
                $this->setSingleton($class, $definition[0], $definition[1]);
695 1
                continue;
696
            }
697
698 10
            $this->setSingleton($class, $definition);
699
        }
700 10
    }
701
702
    /**
703
     * @param bool $value whether to attempt to resolve elements in array dependencies
704
     * @since 2.0.37
705
     */
706 1
    public function setResolveArrays($value)
707
    {
708 1
        $this->_resolveArrays = (bool) $value;
709 1
    }
710
}
711