Passed
Push — master ( ce8019...6eec84 )
by Alexander
01:54
created

DefinitionResolver   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 89.47%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 17
c 3
b 0
f 0
dl 0
loc 51
ccs 17
cts 19
cp 0.8947
rs 10
wmc 12

3 Methods

Rating   Name   Duplication   Size   Complexity  
A resolveArray() 0 8 2
A ensureResolvable() 0 10 5
A resolve() 0 11 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Factory\Definitions;
6
7
use Psr\Container\ContainerInterface;
8
9
class DefinitionResolver
10
{
11
    /**
12
     * Resolves dependencies by replacing them with the actual object instances.
13
     * @param ContainerInterface $container
14
     * @param DefinitionInterface[] $dependencies the dependencies
15
     * @return array the resolved dependencies
16
     */
17 39
    public static function resolveArray(ContainerInterface $container, array $dependencies): array
18
    {
19 39
        $result = [];
20 39
        foreach ($dependencies as $key => $definition) {
21 39
            $result[$key] = self::resolve($container, $definition);
22
        }
23
24 37
        return $result;
25
    }
26
27
    /**
28
     * This function resolves a definition recursively, checking for loops.
29
     * @param ContainerInterface $container
30
     * @param mixed $definition
31
     * @return mixed
32
     */
33 39
    public static function resolve(ContainerInterface $container, $definition)
34
    {
35 39
        if ($definition instanceof DefinitionInterface) {
36 38
            $definition = $definition->resolve($container);
37 7
        } elseif (!is_string($definition) && is_callable($definition, true)) {
38
            return (new CallableDefinition($definition))->resolve($container);
39 7
        } elseif (is_array($definition)) {
40 7
            return self::resolveArray($container, $definition);
41
        }
42
43 37
        return $definition;
44
    }
45
46
    /**
47
     * @param mixed $value
48
     * @return mixed
49
     */
50 10
    public static function ensureResolvable($value)
51
    {
52 10
        if ($value instanceof DefinitionInterface || is_array($value)) {
53 2
            return $value;
54
        }
55 8
        if (!is_string($value) && is_callable($value, true)) {
56
            return new CallableDefinition($value);
57
        }
58
59 8
        return new ValueDefinition($value);
60
    }
61
}
62