1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the Stack package. |
4
|
|
|
* |
5
|
|
|
* (c) Andrzej Kostrzewa <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Stack\DI\Resolver; |
12
|
|
|
|
13
|
|
|
use Stack\DI\Exception; |
14
|
|
|
use Stack\DI\Injection\LazyInterface; |
15
|
|
|
|
16
|
|
|
class ParameterResolver |
17
|
|
|
{ |
18
|
|
|
public function resolve($class, $params, $mergeParams = []) |
19
|
|
|
{ |
20
|
|
|
$this->mergeParams($class, $params, $mergeParams); |
21
|
|
|
|
22
|
|
|
return $params; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Merges the params with overrides; also invokes Lazy values. |
27
|
|
|
* |
28
|
|
|
* @param string $class The params are on this class. |
29
|
|
|
* @param array $params The constructor parameters. |
30
|
|
|
* @param array $mergeParams An array of override parameters. |
31
|
|
|
* |
32
|
|
|
* @throws Exception\MissingParam |
33
|
|
|
* |
34
|
|
|
* @return string[]|null |
35
|
|
|
*/ |
36
|
|
|
protected function mergeParams($class, &$params, array $mergeParams = []) |
37
|
|
|
{ |
38
|
|
|
if (empty($mergeParams)) { |
39
|
|
|
$this->mergeParamsEmpty($class, $params); |
40
|
|
|
|
41
|
|
|
return; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$positionOfParam = 0; |
45
|
|
|
foreach ($params as $key => $value) { |
46
|
|
|
if (array_key_exists($positionOfParam, $mergeParams)) { |
47
|
|
|
$value = $mergeParams[$positionOfParam]; |
48
|
|
|
} elseif (array_key_exists($key, $mergeParams)) { |
49
|
|
|
$value = $mergeParams[$key]; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
if ($value instanceof UnresolvedParam) { |
53
|
|
|
throw Exception::missingParam($class, $value->getName()); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
if ($value instanceof LazyInterface) { |
57
|
|
|
$value = $value(); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$params[$key] = $value; |
61
|
|
|
|
62
|
|
|
$positionOfParam++; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Load the Lazy values in params when the mergeParams are empty. |
68
|
|
|
* |
69
|
|
|
* @param string $class The params are on this class. |
70
|
|
|
* @param array $params The constructor parameters. |
71
|
|
|
* |
72
|
|
|
* @throws Exception\MissingParam |
73
|
|
|
* |
74
|
|
|
* @return null |
75
|
|
|
*/ |
76
|
|
|
protected function mergeParamsEmpty($class, &$params) |
77
|
|
|
{ |
78
|
|
|
foreach ($params as $key => $value) { |
79
|
|
|
if ($value instanceof UnresolvedParam) { |
80
|
|
|
throw Exception::missingParam($class, $value->getName()); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
if ($value instanceof LazyInterface) { |
84
|
|
|
$params[$key] = $value(); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|