|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Phoole (PHP7.2+) |
|
5
|
|
|
* |
|
6
|
|
|
* @category Library |
|
7
|
|
|
* @package Phoole\Middleware |
|
8
|
|
|
* @copyright Copyright (c) 2019 Hong Zhang |
|
9
|
|
|
*/ |
|
10
|
|
|
declare(strict_types=1); |
|
11
|
|
|
|
|
12
|
|
|
namespace Phoole\Middleware; |
|
13
|
|
|
|
|
14
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
15
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
16
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
17
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Queue |
|
21
|
|
|
* |
|
22
|
|
|
* Queue of middlewares |
|
23
|
|
|
* |
|
24
|
|
|
* @package Phoole\Middleware |
|
25
|
|
|
*/ |
|
26
|
|
|
class Queue implements RequestHandlerInterface, MiddlewareInterface |
|
27
|
|
|
{ |
|
28
|
|
|
/** |
|
29
|
|
|
* @var MiddlewareInterface[] |
|
30
|
|
|
*/ |
|
31
|
|
|
protected $middlewares = []; |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @var RequestHandlerInterface |
|
35
|
|
|
*/ |
|
36
|
|
|
protected $defaultHandler; |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* Constructor |
|
40
|
|
|
* |
|
41
|
|
|
* @param RequestHandlerInterface $defaultHandler |
|
42
|
|
|
*/ |
|
43
|
|
|
public function __construct(RequestHandlerInterface $defaultHandler = null) |
|
44
|
|
|
{ |
|
45
|
|
|
$this->defaultHandler = $defaultHandler; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* add middleware[s] to the queue |
|
50
|
|
|
* |
|
51
|
|
|
* @param MiddlewareInterface ...$middlewares |
|
52
|
|
|
* @return $this |
|
53
|
|
|
*/ |
|
54
|
|
|
public function add(MiddlewareInterface ...$middlewares): Queue |
|
55
|
|
|
{ |
|
56
|
|
|
foreach ($middlewares as $m) { |
|
57
|
|
|
$this->middlewares[] = $m; |
|
58
|
|
|
} |
|
59
|
|
|
return $this; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* {@inheritDoc} |
|
64
|
|
|
* |
|
65
|
|
|
* @throws \LogicException if default handler not set |
|
66
|
|
|
*/ |
|
67
|
|
|
public function handle(ServerRequestInterface $request): ResponseInterface |
|
68
|
|
|
{ |
|
69
|
|
|
if (is_null($this->defaultHandler)) { |
|
70
|
|
|
throw new \LogicException('default handler not set'); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
$handler = $this->defaultHandler; |
|
74
|
|
|
foreach (array_reverse($this->middlewares) as $middleware) { |
|
75
|
|
|
$handler = new Handler($middleware, $handler); |
|
76
|
|
|
} |
|
77
|
|
|
return $handler->handle($request); |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
/** |
|
81
|
|
|
* {@inheritDoc} |
|
82
|
|
|
*/ |
|
83
|
|
|
public function process( |
|
84
|
|
|
ServerRequestInterface $request, |
|
85
|
|
|
RequestHandlerInterface $handler |
|
86
|
|
|
): ResponseInterface { |
|
87
|
|
|
$this->defaultHandler = $handler; |
|
88
|
|
|
return $this->handle($request); |
|
89
|
|
|
} |
|
90
|
|
|
} |
|
91
|
|
|
|