1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\RequestModel; |
6
|
|
|
|
7
|
|
|
use Psr\Container\ContainerInterface; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
10
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
11
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
12
|
|
|
use ReflectionFunction; |
13
|
|
|
use ReflectionFunctionAbstract; |
14
|
|
|
use ReflectionMethod; |
15
|
|
|
use Yiisoft\Injector\Injector; |
16
|
|
|
|
17
|
|
|
final class CallableWrapper implements MiddlewareInterface |
18
|
|
|
{ |
19
|
|
|
private ContainerInterface $container; |
20
|
|
|
private RequestModelFactory $factory; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var callable |
24
|
|
|
*/ |
25
|
|
|
private $callback; |
26
|
|
|
|
27
|
6 |
|
public function __construct(ContainerInterface $container, RequestModelFactory $factory, callable $callback) |
28
|
|
|
{ |
29
|
6 |
|
$this->container = $container; |
30
|
6 |
|
$this->factory = $factory; |
31
|
6 |
|
$this->callback = $callback; |
32
|
|
|
} |
33
|
|
|
|
34
|
4 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
35
|
|
|
{ |
36
|
4 |
|
$params = array_merge( |
37
|
4 |
|
[$request, $handler], |
38
|
4 |
|
$this->factory->createInstances($request, $this->getHandlerParams()) |
39
|
|
|
); |
40
|
4 |
|
$response = (new Injector($this->container))->invoke($this->callback, $params); |
41
|
4 |
|
return $response instanceof MiddlewareInterface ? $response->process($request, $handler) : $response; |
42
|
|
|
} |
43
|
|
|
|
44
|
4 |
|
private function getHandlerParams(): array |
45
|
|
|
{ |
46
|
|
|
return $this |
47
|
4 |
|
->getReflector() |
48
|
4 |
|
->getParameters(); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @throws \ReflectionException |
53
|
|
|
* |
54
|
|
|
* @return ReflectionFunction|ReflectionFunctionAbstract|ReflectionMethod |
55
|
|
|
*/ |
56
|
4 |
|
private function getReflector(): ReflectionFunctionAbstract |
57
|
|
|
{ |
58
|
4 |
|
if (is_object($this->callback)) { |
59
|
3 |
|
$this->callback = [$this->callback, '__invoke']; |
60
|
|
|
} |
61
|
|
|
|
62
|
4 |
|
if (is_array($this->callback)) { |
63
|
4 |
|
return new ReflectionMethod($this->callback[0], $this->callback[1]); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return new ReflectionFunction($this->callback); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|