Passed
Pull Request — master (#93)
by Sergei
04:47 queued 02:36
created

DefinitionResolver::ensureResolvable()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 14
ccs 7
cts 7
cp 1
rs 10
cc 4
nc 3
nop 1
crap 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
/**
13
 * @internal
14
 */
15
final class DefinitionResolver
16
{
17
    /**
18
     * Resolves dependencies by replacing them with the actual object instances.
19
     *
20
     * @param array $dependencies The dependencies.
21
     *
22
     * @psalm-param array<string,mixed> $dependencies
23
     *
24
     * @return array The resolved dependencies.
25
     *
26
     * @psalm-return array<string,mixed>
27
     */
28 44
    public static function resolveArray(ContainerInterface $container, array $dependencies): array
29
    {
30 44
        $result = [];
31
        /** @var mixed $definition */
32 44
        foreach ($dependencies as $key => $definition) {
33 43
            if ($definition instanceof ParameterDefinition && !$definition->hasValue()) {
34 19
                continue;
35
            }
36
37
            /** @var mixed */
38 42
            $result[$key] = self::resolve($container, $definition);
39
        }
40
41 42
        return $result;
42
    }
43
44
    /**
45
     * This function resolves a definition recursively, checking for loops.
46
     *
47
     * @param mixed $definition
48
     *
49
     * @return mixed
50
     */
51 43
    public static function resolve(ContainerInterface $container, $definition)
52
    {
53 43
        if ($definition instanceof DefinitionInterface) {
54
            /** @var mixed $definition */
55 41
            $definition = $definition->resolve($container);
56 13
        } elseif (is_array($definition)) {
57
            /** @psalm-var array<string,mixed> $definition */
58 11
            return self::resolveArray($container, $definition);
59
        }
60
61 41
        return $definition;
62
    }
63
64
    /**
65
     * @param mixed $value
66
     *
67
     * @throws InvalidConfigException
68
     *
69
     * @return array|CallableDefinition|DefinitionInterface|ValueDefinition
70
     */
71 15
    public static function ensureResolvable($value)
72
    {
73 15
        if ($value instanceof ReferenceInterface || is_array($value)) {
74 1
            return $value;
75
        }
76
77 14
        if ($value instanceof DefinitionInterface) {
78 1
            throw new InvalidConfigException(
79
                'Only references are allowed in parameters, a definition object was provided: ' .
80 1
                var_export($value, true)
81
            );
82
        }
83
84 13
        return new ValueDefinition($value);
85
    }
86
}
87