Passed
Pull Request — master (#85)
by Sergei
02:17
created

DefinitionResolver   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Test Coverage

Coverage 90%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 11
eloc 18
c 1
b 1
f 0
dl 0
loc 67
ccs 18
cts 20
cp 0.9
rs 10

3 Methods

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