Passed
Push — master ( c0f6da...b424db )
by Jelmer
04:57
created

ApplicationStack::withMiddleware()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 1
crap 2
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