|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Router; |
|
6
|
|
|
|
|
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
8
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
9
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
10
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
11
|
|
|
|
|
12
|
|
|
final class MiddlewareStack implements MiddlewareStackInterface |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* Contains a stack of middleware wrapped in handlers. |
|
16
|
|
|
* Each handler points to the handler of middleware that will be processed next. |
|
17
|
|
|
* @var RequestHandlerInterface|null stack of middleware |
|
18
|
|
|
*/ |
|
19
|
|
|
private ?RequestHandlerInterface $stack = null; |
|
20
|
|
|
|
|
21
|
|
|
public function build(array $middlewares, RequestHandlerInterface $fallbackHandler): MiddlewareStackInterface |
|
22
|
|
|
{ |
|
23
|
|
|
$handler = $fallbackHandler; |
|
24
|
|
|
foreach ($middlewares as $middleware) { |
|
25
|
|
|
$handler = $this->wrap($middleware, $handler); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
$new = clone $this; |
|
29
|
|
|
$new->stack = $handler; |
|
30
|
|
|
|
|
31
|
|
|
return $new; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public function handle(ServerRequestInterface $request): ResponseInterface |
|
35
|
|
|
{ |
|
36
|
|
|
if ($this->isEmpty()) { |
|
37
|
|
|
throw new \RuntimeException('Stack is empty.'); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
return $this->stack->handle($request); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
public function reset(): void |
|
44
|
|
|
{ |
|
45
|
|
|
$this->stack = null; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
public function isEmpty(): bool |
|
49
|
|
|
{ |
|
50
|
|
|
return $this->stack === null; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Wraps handler by middlewares |
|
55
|
|
|
*/ |
|
56
|
|
|
private function wrap(MiddlewareInterface $middleware, RequestHandlerInterface $handler): RequestHandlerInterface |
|
57
|
|
|
{ |
|
58
|
|
|
return new class($middleware, $handler) implements RequestHandlerInterface { |
|
59
|
|
|
private MiddlewareInterface $middleware; |
|
60
|
|
|
private RequestHandlerInterface $handler; |
|
61
|
|
|
|
|
62
|
|
|
public function __construct(MiddlewareInterface $middleware, RequestHandlerInterface $handler) |
|
63
|
|
|
{ |
|
64
|
|
|
$this->middleware = $middleware; |
|
65
|
|
|
$this->handler = $handler; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
public function handle(ServerRequestInterface $request): ResponseInterface |
|
69
|
|
|
{ |
|
70
|
|
|
return $this->middleware->process($request, $this->handler); |
|
71
|
|
|
} |
|
72
|
|
|
}; |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|