|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Northwoods\Broker; |
|
5
|
|
|
|
|
6
|
|
|
use OutOfBoundsException; |
|
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
|
|
|
class Broker implements |
|
13
|
|
|
MiddlewareInterface, |
|
14
|
|
|
RequestHandlerInterface |
|
15
|
|
|
{ |
|
16
|
|
|
/** @var MiddlewareInterface[] */ |
|
17
|
|
|
private $middleware = []; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Add middleware to the end of the stack |
|
21
|
|
|
*/ |
|
22
|
2 |
|
public function append(MiddlewareInterface ...$middleware): self |
|
23
|
|
|
{ |
|
24
|
2 |
|
array_push($this->middleware, ...$middleware); |
|
25
|
|
|
|
|
26
|
2 |
|
return $this; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* Add middleware to the beginning of the stack |
|
31
|
|
|
*/ |
|
32
|
1 |
|
public function prepend(MiddlewareInterface ...$middleware): self |
|
33
|
|
|
{ |
|
34
|
1 |
|
array_unshift($this->middleware, ...$middleware); |
|
35
|
|
|
|
|
36
|
1 |
|
return $this; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
// RequestHandlerInterface |
|
40
|
3 |
|
public function handle(ServerRequestInterface $request): ResponseInterface |
|
41
|
|
|
{ |
|
42
|
3 |
|
$broker = clone $this; |
|
43
|
|
|
|
|
44
|
3 |
|
return $broker->nextMiddleware()->process($request, $broker); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
// MiddlewareInterface |
|
48
|
2 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
49
|
|
|
{ |
|
50
|
|
|
try { |
|
51
|
2 |
|
return $this->handle($request); |
|
52
|
2 |
|
} catch (OutOfBoundsException $e) { |
|
53
|
2 |
|
return $handler->handle($request); |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* @throws OutOfBoundsException If no middleware is available |
|
59
|
|
|
*/ |
|
60
|
3 |
|
private function nextMiddleware(): MiddlewareInterface |
|
61
|
|
|
{ |
|
62
|
3 |
|
$middleware = array_shift($this->middleware); |
|
63
|
|
|
|
|
64
|
3 |
|
if ($middleware === null) { |
|
65
|
3 |
|
throw new OutOfBoundsException("End of middleware stack"); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
2 |
|
return $middleware; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|