1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the rybakit/arguments-resolver package. |
7
|
|
|
* |
8
|
|
|
* (c) Eugene Leonovich <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace ArgumentsResolver; |
15
|
|
|
|
16
|
|
|
abstract class ArgumentsResolver |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @var \ReflectionFunctionAbstract |
20
|
|
|
*/ |
21
|
|
|
protected $reflection; |
22
|
|
|
|
23
|
16 |
|
public function __construct($function) |
24
|
|
|
{ |
25
|
16 |
|
$this->reflection = $function instanceof \ReflectionFunctionAbstract |
26
|
16 |
|
? $function |
27
|
|
|
: ReflectionFactory::create($function); |
28
|
16 |
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Resolves function arguments. |
32
|
|
|
* |
33
|
|
|
* @throws UnresolvableArgumentException |
34
|
|
|
* @throws \ReflectionException |
35
|
|
|
*/ |
36
|
16 |
|
public function resolve(array $parameters) : array |
37
|
|
|
{ |
38
|
16 |
|
if (!$number = $this->reflection->getNumberOfParameters()) { |
39
|
2 |
|
return []; |
40
|
|
|
} |
41
|
|
|
|
42
|
14 |
|
$arguments = \array_fill(0, $number, null); |
43
|
|
|
|
44
|
14 |
|
foreach ($this->getParameters() as $pos => $parameter) { |
45
|
14 |
|
$result = $this->match($parameter, $parameters); |
46
|
|
|
|
47
|
14 |
|
if ($result) { |
48
|
6 |
|
$arguments[$pos] = $result[1]; |
49
|
6 |
|
unset($parameters[$result[0]]); |
50
|
6 |
|
continue; |
51
|
|
|
} |
52
|
|
|
|
53
|
8 |
|
if ($parameter->isDefaultValueAvailable()) { |
54
|
3 |
|
$arguments[$pos] = $parameter->getDefaultValue(); |
55
|
3 |
|
continue; |
56
|
|
|
} |
57
|
|
|
|
58
|
5 |
|
throw UnresolvableArgumentException::fromParameter($parameter); |
59
|
|
|
} |
60
|
|
|
|
61
|
9 |
|
return $arguments; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Returns an array of reflection parameters. |
66
|
|
|
* |
67
|
|
|
* @return \ReflectionParameter[] |
68
|
|
|
*/ |
69
|
3 |
|
protected function getParameters() : array |
70
|
|
|
{ |
71
|
3 |
|
return $this->reflection->getParameters(); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* Returns the [key, value] pair if the parameter is matched or null otherwise. |
76
|
|
|
*/ |
77
|
|
|
abstract protected function match(\ReflectionParameter $parameter, array $parameters) : ?array; |
78
|
|
|
} |
79
|
|
|
|