1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Class RecursiveDispatcher |
4
|
|
|
* |
5
|
|
|
* A simple middleware dispatcher based on Slim |
6
|
|
|
* |
7
|
|
|
* @see https://github.com/slimphp/Slim/blob/de07f779d229ec06080259a816b0740de830438c/Slim/MiddlewareDispatcher.php |
8
|
|
|
* |
9
|
|
|
* @created 15.04.2020 |
10
|
|
|
* @author smiley <[email protected]> |
11
|
|
|
* @copyright 2020 smiley |
12
|
|
|
* @license MIT |
13
|
|
|
*/ |
14
|
|
|
|
15
|
|
|
namespace chillerlan\HTTP\Psr15; |
16
|
|
|
|
17
|
|
|
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface}; |
18
|
|
|
use Psr\Http\Server\{MiddlewareInterface, RequestHandlerInterface}; |
19
|
|
|
|
20
|
|
|
class RecursiveDispatcher implements RequestHandlerInterface{ |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Tip of the middleware call stack |
24
|
|
|
*/ |
25
|
|
|
protected RequestHandlerInterface $tip; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* RecursiveDispatcher constructor. |
29
|
|
|
*/ |
30
|
|
|
public function __construct(RequestHandlerInterface $kernel){ |
31
|
|
|
$this->tip = $kernel; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Add a new middleware to the stack |
36
|
|
|
* |
37
|
|
|
* Middleware are organized as a stack. That means middleware |
38
|
|
|
* that have been added before will be executed after the newly |
39
|
|
|
* added one (last in, first out). |
40
|
|
|
*/ |
41
|
|
|
public function add(MiddlewareInterface $middleware):RecursiveDispatcher{ |
42
|
|
|
|
43
|
|
|
$this->tip = new class ($middleware, $this->tip) implements RequestHandlerInterface{ |
44
|
|
|
|
45
|
|
|
private MiddlewareInterface $middleware; |
46
|
|
|
private RequestHandlerInterface $next; |
47
|
|
|
|
48
|
|
|
public function __construct(MiddlewareInterface $middleware, RequestHandlerInterface $next){ |
49
|
|
|
$this->middleware = $middleware; |
50
|
|
|
$this->next = $next; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function handle(ServerRequestInterface $request):ResponseInterface{ |
54
|
|
|
return $this->middleware->process($request, $this->next); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
}; |
58
|
|
|
|
59
|
|
|
return $this; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param \Psr\Http\Server\MiddlewareInterface[] $middlewareStack |
64
|
|
|
* |
65
|
|
|
* @throws \chillerlan\HTTP\Psr15\MiddlewareException |
66
|
|
|
*/ |
67
|
|
|
public function addStack(iterable $middlewareStack):RecursiveDispatcher{ |
68
|
|
|
|
69
|
|
|
foreach($middlewareStack as $middleware){ |
70
|
|
|
|
71
|
|
|
if(!$middleware instanceof MiddlewareInterface){ |
72
|
|
|
throw new MiddlewareException('invalid middleware'); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
$this->add($middleware); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return $this; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
/** |
82
|
|
|
* @inheritDoc |
83
|
|
|
*/ |
84
|
|
|
public function handle(ServerRequestInterface $request):ResponseInterface{ |
85
|
|
|
return $this->tip->handle($request); |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
} |
89
|
|
|
|