Container::resolveCallableDependencies()   F
last analyzed

Complexity

Conditions 33
Paths 222

Size

Total Lines 80
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 44
CRAP Score 36.9617

Importance

Changes 0
Metric Value
cc 33
eloc 57
nc 222
nop 2
dl 0
loc 80
ccs 44
cts 52
cp 0.8462
crap 36.9617
rs 3.0583
c 0
b 0
f 0

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

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
670 2
                    $isClass = false;
671 2
                    foreach ($class->getTypes() as $type) {
0 ignored issues
show
Bug introduced by
The method getTypes() does not exist on ReflectionType. It seems like you code against a sub-type of ReflectionType such as ReflectionUnionType. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

671
                    foreach ($class->/** @scrutinizer ignore-call */ getTypes() as $type) {
Loading history...
672 2
                        if (!$type->isBuiltin()) {
673 2
                            $class = $type;
674 2
                            $isClass = true;
675 2
                            break;
676
                        }
677
                    }
678
                } else {
679 8
                    $isClass = $class !== null && !$class->isBuiltin();
680
                }
681
            } else {
682
                $class = $param->getClass();
683
                $isClass = $class !== null;
684
            }
685
686 8
            if ($isClass) {
687 6
                $className = $class->getName();
0 ignored issues
show
Bug introduced by
The method getName() does not exist on ReflectionType. It seems like you code against a sub-type of ReflectionType such as ReflectionNamedType. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

687
                /** @scrutinizer ignore-call */ 
688
                $className = $class->getName();
Loading history...
Bug introduced by
The method getName() does not exist on ReflectionUnionType. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

687
                /** @scrutinizer ignore-call */ 
688
                $className = $class->getName();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
688 6
                if (PHP_VERSION_ID >= 50600 && $param->isVariadic()) {
689 1
                    $args = array_merge($args, array_values($params));
690 1
                    break;
691
                }
692
693 5
                if ($associative && isset($params[$name]) && $params[$name] instanceof $className) {
694
                    $args[] = $params[$name];
695
                    unset($params[$name]);
696 5
                } elseif (!$associative && isset($params[0]) && $params[0] instanceof $className) {
697 1
                    $args[] = array_shift($params);
698 5
                } elseif (isset(Yii::$app) && Yii::$app->has($name) && ($obj = Yii::$app->get($name)) instanceof $className) {
699 1
                    $args[] = $obj;
700
                } else {
701
                    // If the argument is optional we catch not instantiable exceptions
702
                    try {
703 5
                        $args[] = $this->get($className);
704 1
                    } catch (NotInstantiableException $e) {
705 1
                        if ($param->isDefaultValueAvailable()) {
706 1
                            $args[] = $param->getDefaultValue();
707
                        } else {
708 5
                            throw $e;
709
                        }
710
                    }
711
                }
712 4
            } elseif ($associative && isset($params[$name])) {
713 2
                $args[] = $params[$name];
714 2
                unset($params[$name]);
715 4
            } elseif (!$associative && count($params)) {
716 3
                $args[] = array_shift($params);
717 3
            } elseif ($param->isDefaultValueAvailable()) {
718 3
                $args[] = $param->getDefaultValue();
719
            } elseif (!$param->isOptional()) {
720
                $funcName = $reflection->getName();
721
                throw new InvalidConfigException("Missing required parameter \"$name\" when calling \"$funcName\".");
722
            }
723
        }
724
725 13
        foreach ($params as $value) {
726
            $args[] = $value;
727
        }
728
729 13
        return $args;
730
    }
731
732
    /**
733
     * Registers class definitions within this container.
734
     *
735
     * @param array $definitions array of definitions. There are two allowed formats of array.
736
     * The first format:
737
     *  - key: class name, interface name or alias name. The key will be passed to the [[set()]] method
738
     *    as a first argument `$class`.
739
     *  - value: the definition associated with `$class`. Possible values are described in
740
     *    [[set()]] documentation for the `$definition` parameter. Will be passed to the [[set()]] method
741
     *    as the second argument `$definition`.
742
     *
743
     * Example:
744
     * ```php
745
     * $container->setDefinitions([
746
     *     'yii\web\Request' => 'app\components\Request',
747
     *     'yii\web\Response' => [
748
     *         'class' => 'app\components\Response',
749
     *         'format' => 'json'
750
     *     ],
751
     *     'foo\Bar' => function () {
752
     *         $qux = new Qux;
753
     *         $foo = new Foo($qux);
754
     *         return new Bar($foo);
755
     *     }
756
     * ]);
757
     * ```
758
     *
759
     * The second format:
760
     *  - key: class name, interface name or alias name. The key will be passed to the [[set()]] method
761
     *    as a first argument `$class`.
762
     *  - value: array of two elements. The first element will be passed the [[set()]] method as the
763
     *    second argument `$definition`, the second one — as `$params`.
764
     *
765
     * Example:
766
     * ```php
767
     * $container->setDefinitions([
768
     *     'foo\Bar' => [
769
     *          ['class' => 'app\Bar'],
770
     *          [Instance::of('baz')]
771
     *      ]
772
     * ]);
773
     * ```
774
     *
775
     * @see set() to know more about possible values of definitions
776
     * @since 2.0.11
777
     */
778 9
    public function setDefinitions(array $definitions)
779
    {
780 9
        foreach ($definitions as $class => $definition) {
781 9
            if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition && is_array($definition[1])) {
782 1
                $this->set($class, $definition[0], $definition[1]);
783 1
                continue;
784
            }
785
786 9
            $this->set($class, $definition);
787
        }
788
    }
789
790
    /**
791
     * Registers class definitions as singletons within this container by calling [[setSingleton()]].
792
     *
793
     * @param array $singletons array of singleton definitions. See [[setDefinitions()]]
794
     * for allowed formats of array.
795
     *
796
     * @see setDefinitions() for allowed formats of $singletons parameter
797
     * @see setSingleton() to know more about possible values of definitions
798
     * @since 2.0.11
799
     */
800 10
    public function setSingletons(array $singletons)
801
    {
802 10
        foreach ($singletons as $class => $definition) {
803 10
            if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition) {
804 1
                $this->setSingleton($class, $definition[0], $definition[1]);
805 1
                continue;
806
            }
807
808 10
            $this->setSingleton($class, $definition);
809
        }
810
    }
811
812
    /**
813
     * @param bool $value whether to attempt to resolve elements in array dependencies
814
     * @since 2.0.37
815
     */
816 1
    public function setResolveArrays($value)
817
    {
818 1
        $this->_resolveArrays = (bool) $value;
819
    }
820
}
821