|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the jade/jade package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Slince <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Jade\HttpKernel; |
|
13
|
|
|
|
|
14
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
15
|
|
|
|
|
16
|
|
|
class ArgumentResolver implements ArgumentResolverInterface |
|
17
|
|
|
{ |
|
18
|
|
|
protected $defaults = []; |
|
19
|
|
|
|
|
20
|
|
|
public function __construct($defaults = []) |
|
21
|
|
|
{ |
|
22
|
|
|
$this->defaults = $defaults; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* {@inheritdoc} |
|
27
|
|
|
*/ |
|
28
|
|
|
public function getArguments(ServerRequestInterface $request, callable $controller) |
|
29
|
|
|
{ |
|
30
|
|
|
$this->addDefault('request', $request); |
|
31
|
|
|
$providedArguments = array_merge( |
|
32
|
|
|
$this->defaults, |
|
33
|
|
|
$request->getAttribute('_route')->getArguments() |
|
34
|
|
|
); |
|
35
|
|
|
$arguments = []; |
|
36
|
|
|
$parameters = $this->createArgumentMetadata($controller); |
|
37
|
|
|
foreach ($parameters as $parameter) { |
|
38
|
|
|
$name = $parameter->getName(); |
|
|
|
|
|
|
39
|
|
|
$arguments[$name] = isset($providedArguments[$name]) |
|
40
|
|
|
? $providedArguments[$name] : ( |
|
41
|
|
|
$parameter->isOptional() ? $parameter->getDefaultValue() : null |
|
42
|
|
|
); |
|
43
|
|
|
} |
|
44
|
|
|
return $arguments; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* 添加一个默认参数 |
|
49
|
|
|
* |
|
50
|
|
|
* @param string $name |
|
51
|
|
|
* @param mixed $value |
|
52
|
|
|
*/ |
|
53
|
|
|
public function addDefault($name, $value) |
|
54
|
|
|
{ |
|
55
|
|
|
$this->defaults[$name] = $value; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* 设置默认 |
|
60
|
|
|
* |
|
61
|
|
|
* @param array $defaults |
|
62
|
|
|
*/ |
|
63
|
|
|
public function setDefaults(array $defaults): void |
|
64
|
|
|
{ |
|
65
|
|
|
$this->defaults = $defaults; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* 分析控制器的参数 |
|
70
|
|
|
* |
|
71
|
|
|
* @param callable $controller |
|
72
|
|
|
* @return \ReflectionParameter[] |
|
73
|
|
|
* @throws \ReflectionException |
|
74
|
|
|
*/ |
|
75
|
|
|
protected function createArgumentMetadata($controller) |
|
76
|
|
|
{ |
|
77
|
|
|
if (\is_array($controller)) { |
|
78
|
|
|
$reflection = new \ReflectionMethod($controller[0], $controller[1]); |
|
79
|
|
|
} elseif (\is_object($controller) && !$controller instanceof \Closure) { |
|
80
|
|
|
$reflection = (new \ReflectionObject($controller))->getMethod('__invoke'); |
|
81
|
|
|
} else { |
|
82
|
|
|
$reflection = new \ReflectionFunction($controller); |
|
83
|
|
|
} |
|
84
|
|
|
return $reflection->getParameters(); |
|
85
|
|
|
} |
|
86
|
|
|
} |