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

DefinitionResolver::resolve()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5.0488

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 7
c 2
b 0
f 0
nc 4
nop 2
dl 0
loc 11
ccs 7
cts 8
cp 0.875
crap 5.0488
rs 9.6111
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