Completed
Push — master ( b0867d...8ab030 )
by Alexander
24s queued 11s
created

Normalizer   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 10
eloc 15
dl 0
loc 67
rs 10
c 0
b 0
f 0

1 Method

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