1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
namespace Venta\Routing; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
6
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
7
|
|
|
use Venta\Contracts\Routing\Delegate as DelegateContract; |
8
|
|
|
use Venta\Contracts\Routing\Middleware; |
9
|
|
|
use Venta\Contracts\Routing\MiddlewarePipeline as MiddlewarePipelineContract; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class MiddlewarePipeline |
13
|
|
|
* |
14
|
|
|
* @package Venta\Routing |
15
|
|
|
*/ |
16
|
|
|
class MiddlewarePipeline implements MiddlewarePipelineContract |
17
|
|
|
{ |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var Middleware[] |
21
|
|
|
*/ |
22
|
|
|
private $middlewares = []; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @inheritDoc |
26
|
|
|
*/ |
27
|
3 |
|
public function process(ServerRequestInterface $request, DelegateContract $delegate): ResponseInterface |
28
|
|
|
{ |
29
|
3 |
|
foreach (array_reverse($this->middlewares) as $middleware) { |
30
|
2 |
|
$delegate = $this->createDelegate($middleware, $delegate); |
31
|
|
|
} |
32
|
|
|
|
33
|
3 |
|
return $delegate->next($request); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @inheritDoc |
38
|
|
|
*/ |
39
|
3 |
|
public function withMiddleware(Middleware $middleware): MiddlewarePipelineContract |
40
|
|
|
{ |
41
|
3 |
|
$pipeline = clone $this; |
42
|
3 |
|
$pipeline->middlewares[] = $middleware; |
43
|
|
|
|
44
|
3 |
|
return $pipeline; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param Middleware $middleware |
49
|
|
|
* @param DelegateContract $nextDelegate |
50
|
|
|
* @return DelegateContract |
51
|
|
|
*/ |
52
|
|
|
protected function createDelegate($middleware, DelegateContract $nextDelegate): DelegateContract |
53
|
|
|
{ |
54
|
|
|
return new class($middleware, $nextDelegate) implements DelegateContract |
55
|
|
|
{ |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @var Middleware |
59
|
|
|
*/ |
60
|
|
|
private $middleware; |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @var DelegateContract |
64
|
|
|
*/ |
65
|
|
|
private $delegate; |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Delegate constructor. |
69
|
|
|
* |
70
|
|
|
* @param Middleware $middleware |
71
|
|
|
* @param DelegateContract $nextDelegate |
72
|
|
|
*/ |
73
|
2 |
|
public function __construct(Middleware $middleware, DelegateContract $nextDelegate) |
74
|
|
|
{ |
75
|
2 |
|
$this->middleware = $middleware; |
76
|
2 |
|
$this->delegate = $nextDelegate; |
77
|
2 |
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* @inheritDoc |
81
|
|
|
*/ |
82
|
2 |
|
public function next(ServerRequestInterface $request): ResponseInterface |
83
|
|
|
{ |
84
|
2 |
|
return $this->middleware->process($request, $this->delegate); |
85
|
|
|
} |
86
|
|
|
}; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
} |