1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Lit\Nimo\Middlewares; |
6
|
|
|
|
7
|
|
|
use Lit\Nimo\Handlers\CallableHandler; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
10
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
11
|
|
|
|
12
|
|
|
class MiddlewarePipe extends AbstractMiddleware |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var CallableHandler |
16
|
|
|
*/ |
17
|
|
|
protected $nextHandler; |
18
|
|
|
/** |
19
|
|
|
* @var MiddlewareInterface[] |
20
|
|
|
*/ |
21
|
|
|
protected $stack = []; |
22
|
|
|
protected $index; |
23
|
|
|
|
24
|
|
|
public function __construct() |
25
|
|
|
{ |
26
|
3 |
|
$this->nextHandler = CallableHandler::wrap(function (ServerRequestInterface $request) { |
27
|
2 |
|
return $this->loop($request); |
28
|
3 |
|
}); |
29
|
3 |
|
} |
30
|
|
|
|
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* append $middleware |
34
|
|
|
* return $this |
35
|
|
|
* note this method would modify $this |
36
|
|
|
* |
37
|
|
|
* @param MiddlewareInterface $middleware |
38
|
|
|
* @return $this |
39
|
|
|
*/ |
40
|
1 |
|
public function append(MiddlewareInterface $middleware): MiddlewarePipe |
41
|
|
|
{ |
42
|
1 |
|
$this->stack[] = $middleware; |
43
|
1 |
|
return $this; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* prepend $middleware |
48
|
|
|
* return $this |
49
|
|
|
* note this method would modify $this |
50
|
|
|
* |
51
|
|
|
* @param MiddlewareInterface $middleware |
52
|
|
|
* @return $this |
53
|
|
|
*/ |
54
|
1 |
|
public function prepend(MiddlewareInterface $middleware): MiddlewarePipe |
55
|
|
|
{ |
56
|
1 |
|
array_unshift($this->stack, $middleware); |
57
|
1 |
|
return $this; |
58
|
|
|
} |
59
|
|
|
|
60
|
3 |
|
protected function main(): ResponseInterface |
61
|
|
|
{ |
62
|
3 |
|
$this->index = 0; |
63
|
|
|
|
64
|
3 |
|
return $this->loop($this->request); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param ServerRequestInterface $request |
69
|
|
|
* @return ResponseInterface |
70
|
|
|
*/ |
71
|
3 |
|
protected function loop(ServerRequestInterface $request): ResponseInterface |
72
|
|
|
{ |
73
|
3 |
|
if (!isset($this->stack[$this->index])) { |
74
|
3 |
|
return $this->delegate($request); |
75
|
|
|
} |
76
|
|
|
|
77
|
2 |
|
return $this->stack[$this->index++]->process($request, $this->nextHandler); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|