-
Notifications
You must be signed in to change notification settings - Fork 0
/
TypeHintRequestResolver.php
87 lines (74 loc) · 2.47 KB
/
TypeHintRequestResolver.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/**
* Qubus\Routing
*
* @link https://github.com/QubusPHP/router
* @copyright 2020
* @author Joshua Parker <[email protected]>
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
declare(strict_types=1);
namespace Qubus\Routing;
use Invoker\ParameterResolver\ParameterResolver;
use Psr\Http\Message\ServerRequestInterface;
use ReflectionClass;
use ReflectionException;
use ReflectionFunctionAbstract;
use function array_diff_key;
final class TypeHintRequestResolver implements ParameterResolver
{
protected ServerRequestInterface $request;
/**
* @throws ReflectionException
*/
public function getParameters(
ReflectionFunctionAbstract $reflection,
array $providedParameters,
array $resolvedParameters
): array {
if (! isset($this->request)) {
return $resolvedParameters;
}
$parameters = $reflection->getParameters();
/**
* Skip parameters already resolved
*/
if (! empty($resolvedParameters)) {
$parameters = array_diff_key($parameters, $resolvedParameters);
}
foreach ($parameters as $index => $parameter) {
$parameterClass = $parameter->getType() && ! $parameter->getType()->isBuiltin()
? new ReflectionClass(objectOrClass: $parameter->getType()->getName())
: null;
if (! $parameterClass) {
continue;
}
if ($parameterClass->implementsInterface(interface: ServerRequestInterface::class)) {
$resolvedParameters[$index] = $this->createRequestOfType(requestClass: $parameterClass);
}
}
return $resolvedParameters;
}
/**
* @throws ReflectionException
*/
protected function createRequestOfType(ReflectionClass $requestClass): mixed
{
return $requestClass->newInstance(
$this->request->getServerParams(),
$this->request->getUploadedFiles(),
$this->request->getUri(),
$this->request->getMethod(),
$this->request->getBody(),
$this->request->getHeaders(),
$this->request->getCookieParams(),
$this->request->getQueryParams(),
$this->request->getParsedBody(),
$this->request->getProtocolVersion()
);
}
public function setRequest(ServerRequestInterface $request): void
{
$this->request = $request;
}
}