1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace App\Middleware; |
6
|
|
|
|
7
|
|
|
use Psr\Container\ContainerInterface; |
8
|
|
|
use Psr\Http\Message\ResponseFactoryInterface; |
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
10
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
11
|
|
|
use Psr\Http\Message\StreamFactoryInterface; |
12
|
|
|
use Psr\Http\Message\StreamInterface; |
13
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
14
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
15
|
|
|
use Yiisoft\Injector\Injector; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* ActionCaller maps a route to specified class instance and method. |
19
|
|
|
* |
20
|
|
|
* Dependencies are automatically injected into both method |
21
|
|
|
* and constructor based on types specified. |
22
|
|
|
*/ |
23
|
|
|
final class ActionCaller implements MiddlewareInterface |
24
|
|
|
{ |
25
|
|
|
private string $class; |
26
|
|
|
private string $method; |
27
|
|
|
private ContainerInterface $container; |
28
|
|
|
|
29
|
|
|
public function __construct(string $class, string $method, ContainerInterface $container) |
30
|
|
|
{ |
31
|
|
|
$this->class = $class; |
32
|
|
|
$this->method = $method; |
33
|
|
|
$this->container = $container; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
37
|
|
|
{ |
38
|
|
|
$controller = $this->container->get($this->class); |
39
|
|
|
$result = (new Injector($this->container))->invoke([$controller, $this->method], [$request, $handler]); |
40
|
|
|
if ($result instanceof ResponseInterface) { |
41
|
|
|
return $result; |
42
|
|
|
} |
43
|
|
|
if ($result instanceof StreamInterface) { |
44
|
|
|
$stream = $result; |
45
|
|
|
} else { |
46
|
|
|
$stream = $this->container->get(\App\Stream\SmartStreamFactory::class)->createStream($result); |
47
|
|
|
} |
48
|
|
|
return $this->container->get(ResponseFactoryInterface::class)->createResponse()->withBody($stream); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|