Passed
Pull Request — master (#86)
by Dmitriy
02:58
created

DefinitionResolver   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Test Coverage

Coverage 94.74%

Importance

Changes 0
Metric Value
wmc 13
eloc 16
dl 0
loc 60
ccs 18
cts 19
cp 0.9474
rs 10
c 0
b 0
f 0

3 Methods

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