1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace jschreuder\Middle; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
6
|
|
|
use Psr\Http\Message\ResponseInterface; |
7
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
8
|
|
|
|
9
|
|
|
final class ApplicationStack implements ApplicationStackInterface |
10
|
|
|
{ |
11
|
|
|
private \SplStack $stack; |
12
|
|
|
|
13
|
4 |
|
public function __construct(MiddlewareInterface ...$middlewares) |
14
|
|
|
{ |
15
|
4 |
|
$this->stack = new \SplStack(); |
16
|
4 |
|
foreach ($middlewares as $middleware) { |
17
|
3 |
|
$this->stack->push($middleware); |
18
|
|
|
} |
19
|
|
|
} |
20
|
|
|
|
21
|
1 |
|
public function withMiddleware(MiddlewareInterface $middleware): ApplicationStack |
22
|
|
|
{ |
23
|
1 |
|
$stack = clone $this; |
24
|
1 |
|
$stack->stack = clone $this->stack; |
25
|
1 |
|
$stack->stack->push($middleware); |
26
|
1 |
|
return $stack; |
27
|
|
|
} |
28
|
|
|
|
29
|
1 |
|
public function withoutMiddleware(MiddlewareInterface $middleware): ApplicationStack |
30
|
|
|
{ |
31
|
1 |
|
$oldStack = clone $this->stack; |
32
|
1 |
|
$newStack = new \SplStack(); |
33
|
1 |
|
while (!$oldStack->isEmpty()) { |
34
|
1 |
|
$middlewareInstance = $oldStack->shift(); |
35
|
1 |
|
if ($middlewareInstance !== $middleware) { |
36
|
1 |
|
$newStack->push($middlewareInstance); |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
1 |
|
$stack = clone $this; |
41
|
1 |
|
$stack->stack = $newStack; |
42
|
1 |
|
return $stack; |
43
|
|
|
} |
44
|
|
|
|
45
|
3 |
|
public function process(ServerRequestInterface $request): ResponseInterface |
46
|
|
|
{ |
47
|
3 |
|
if ($this->stack->count() === 0) { |
48
|
1 |
|
throw new \RuntimeException('Cannot process with an empty stack'); |
49
|
|
|
} |
50
|
2 |
|
$stack = clone $this->stack; |
51
|
|
|
|
52
|
|
|
/** @var MiddlewareInterface $current */ |
53
|
2 |
|
$current = $stack->pop(); |
54
|
2 |
|
$response = $current->process($request, new RequestHandler($stack)); |
55
|
|
|
|
56
|
2 |
|
return $response; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|