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