Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
14 / 14 |
|
100.00% |
4 / 4 |
CRAP | |
100.00% |
1 / 1 |
Dispatcher | |
100.00% |
14 / 14 |
|
100.00% |
4 / 4 |
7 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
process | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
handle | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
4 | |||
setContainer | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 |
1 | <?php |
2 | |
3 | declare(strict_types=1); |
4 | |
5 | namespace Engelsystem\Middleware; |
6 | |
7 | use Engelsystem\Application; |
8 | use InvalidArgumentException; |
9 | use LogicException; |
10 | use Psr\Http\Message\ResponseInterface; |
11 | use Psr\Http\Message\ServerRequestInterface; |
12 | use Psr\Http\Server\MiddlewareInterface; |
13 | use Psr\Http\Server\RequestHandlerInterface; |
14 | |
15 | class Dispatcher implements MiddlewareInterface, RequestHandlerInterface |
16 | { |
17 | use ResolvesMiddlewareTrait; |
18 | |
19 | protected ?RequestHandlerInterface $next = null; |
20 | |
21 | /** |
22 | * @param MiddlewareInterface[]|string[] $stack |
23 | */ |
24 | public function __construct(protected array $stack = [], protected ?Application $container = null) |
25 | { |
26 | } |
27 | |
28 | /** |
29 | * Process an incoming server request and return a response, optionally delegating |
30 | * response creation to a handler. |
31 | * |
32 | * Could be used to group middleware |
33 | */ |
34 | public function process( |
35 | ServerRequestInterface $request, |
36 | RequestHandlerInterface $handler |
37 | ): ResponseInterface { |
38 | $this->next = $handler; |
39 | |
40 | return $this->handle($request); |
41 | } |
42 | |
43 | /** |
44 | * Handle the request and return a response. |
45 | * |
46 | * It calls all configured middlewares and handles their response |
47 | */ |
48 | public function handle(ServerRequestInterface $request): ResponseInterface |
49 | { |
50 | $middleware = array_shift($this->stack); |
51 | |
52 | if (!$middleware) { |
53 | if ($this->next) { |
54 | return $this->next->handle($request); |
55 | } |
56 | |
57 | throw new LogicException('Middleware queue is empty'); |
58 | } |
59 | |
60 | $middleware = $this->resolveMiddleware($middleware); |
61 | if (!$middleware instanceof MiddlewareInterface) { |
62 | throw new InvalidArgumentException('Middleware is no instance of ' . MiddlewareInterface::class); |
63 | } |
64 | |
65 | return $middleware->process($request, $this); |
66 | } |
67 | |
68 | public function setContainer(Application $container): void |
69 | { |
70 | $this->container = $container; |
71 | } |
72 | } |