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

DefinitionResolver::ensureResolvable()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.3731

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 14
ccs 5
cts 7
cp 0.7143
rs 10
c 0
b 0
f 0
cc 4
nc 3
nop 1
crap 4.3731
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