|
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
|
40 |
|
public static function resolveArray(ContainerInterface $container, array $dependencies): array |
|
23
|
|
|
{ |
|
24
|
40 |
|
$result = []; |
|
25
|
|
|
/** @var mixed $definition */ |
|
26
|
40 |
|
foreach ($dependencies as $key => $definition) { |
|
27
|
40 |
|
if ($definition instanceof ParameterDefinition && !$definition->hasValue()) { |
|
28
|
18 |
|
continue; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** @var mixed */ |
|
32
|
40 |
|
$result[$key] = self::resolve($container, $definition); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
38 |
|
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
|
40 |
|
public static function resolve(ContainerInterface $container, $definition) |
|
46
|
|
|
{ |
|
47
|
40 |
|
if ($definition instanceof DefinitionInterface) { |
|
48
|
|
|
/** @var mixed $definition */ |
|
49
|
38 |
|
$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
|
38 |
|
return $definition; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* @param mixed $value |
|
60
|
|
|
* |
|
61
|
|
|
* @throws InvalidConfigException |
|
62
|
|
|
* |
|
63
|
|
|
* @return array|CallableDefinition|DefinitionInterface|ValueDefinition |
|
64
|
|
|
*/ |
|
65
|
12 |
|
public static function ensureResolvable($value) |
|
66
|
|
|
{ |
|
67
|
12 |
|
if ($value instanceof ReferenceInterface || is_array($value)) { |
|
68
|
1 |
|
return $value; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
11 |
|
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
|
11 |
|
return new ValueDefinition($value); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|