|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
|
|
4
|
|
|
namespace yii\di\definitions; |
|
5
|
|
|
|
|
6
|
|
|
use Psr\Container\ContainerInterface; |
|
7
|
|
|
use yii\di\contracts\DefinitionInterface; |
|
8
|
|
|
use yii\di\exceptions\InvalidConfigException; |
|
9
|
|
|
use yii\di\exceptions\NotInstantiableException; |
|
10
|
|
|
use yii\di\Reference; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Class Definition represents a definition in a container |
|
14
|
|
|
*/ |
|
15
|
|
|
class Normalizer |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* Definition may be defined multiple ways. |
|
19
|
|
|
* Interface name as string: |
|
20
|
|
|
* |
|
21
|
|
|
* ```php |
|
22
|
|
|
* $container->set('interface_name', EngineInterface::class); |
|
23
|
|
|
* ``` |
|
24
|
|
|
* |
|
25
|
|
|
* A closure: |
|
26
|
|
|
* |
|
27
|
|
|
* ```php |
|
28
|
|
|
* $container->set('closure', function($container) { |
|
29
|
|
|
* return new MyClass($container->get('db')); |
|
30
|
|
|
* }); |
|
31
|
|
|
* ``` |
|
32
|
|
|
* |
|
33
|
|
|
* A callable array: |
|
34
|
|
|
* |
|
35
|
|
|
* ```php |
|
36
|
|
|
* $container->set('static_call', [MyClass::class, 'create']); |
|
37
|
|
|
* ``` |
|
38
|
|
|
* |
|
39
|
|
|
* A definition array: |
|
40
|
|
|
* |
|
41
|
|
|
* ```php |
|
42
|
|
|
* $container->set('full_definition', [ |
|
43
|
|
|
* '__class' => EngineMarkOne::class, |
|
44
|
|
|
* '__construct()' => [42], |
|
45
|
|
|
* 'argName' => 'value', |
|
46
|
|
|
* 'setX()' => [42], |
|
47
|
|
|
* ]); |
|
48
|
|
|
* ``` |
|
49
|
|
|
* |
|
50
|
|
|
* @param mixed $config |
|
51
|
|
|
* @param string $id |
|
52
|
|
|
*/ |
|
53
|
|
|
public static function normalize($config, string $id = null): DefinitionInterface |
|
54
|
|
|
{ |
|
55
|
|
|
if ($config instanceof DefinitionInterface) { |
|
56
|
|
|
return $config; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
if (\is_string($config)) { |
|
60
|
|
|
return Reference::to($config); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
if (\is_array($config) |
|
64
|
|
|
&& !(isset($config[0], $config[1]) && count($config) === 2) |
|
65
|
|
|
) { |
|
66
|
|
|
if (empty($config['__class']) && $id) { |
|
67
|
|
|
$config['__class'] = $id; |
|
68
|
|
|
} |
|
69
|
|
|
return new ArrayDefinition($config); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
if (\is_callable($config)) { |
|
73
|
|
|
return new CallableDefinition($config); |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
if (\is_object($config)) { |
|
77
|
|
|
return new ValueDefinition($config); |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
throw new InvalidConfigException('Invalid definition:' . var_export($config, true)); |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|