|
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
|
4 |
|
return $this->getReflector()->getParameters(); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* @throws \ReflectionException |
|
51
|
|
|
* |
|
52
|
|
|
* @return ReflectionFunction|ReflectionFunctionAbstract|ReflectionMethod |
|
53
|
|
|
*/ |
|
54
|
4 |
|
private function getReflector(): ReflectionFunctionAbstract |
|
55
|
|
|
{ |
|
56
|
4 |
|
if (is_object($this->callback)) { |
|
57
|
3 |
|
$this->callback = [$this->callback, '__invoke']; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
4 |
|
if (is_array($this->callback)) { |
|
61
|
4 |
|
return new ReflectionMethod($this->callback[0], $this->callback[1]); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
return new ReflectionFunction($this->callback); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|