Passed
Push — master ( f57bb7...4ff9d0 )
by Jelmer
02:50
created

ApplicationStack::withoutMiddleware()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 10
cts 10
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 3
nop 1
crap 3
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
final class ApplicationStack implements ApplicationStackInterface
9
{
10
    /** @var  \SplStack | HttpMiddlewareInterface[] */
11
    private $stack;
12
13 5
    public function __construct(array $middlewares = [])
14
    {
15 5
        $this->stack = new \SplStack();
16 5
        foreach ($middlewares as $middleware) {
17 3
            if (!$middleware instanceof HttpMiddlewareInterface) {
18 1
                throw new \InvalidArgumentException('All middlewares must implement ApplicationInterface');
19
            }
20 2
            $this->stack->push($middleware);
21
        }
22 4
    }
23
24 1
    public function withMiddleware(HttpMiddlewareInterface $middleware) : ApplicationStack
25
    {
26 1
        $stack = clone $this;
27 1
        $stack->stack = clone $this->stack;
28 1
        $stack->stack->push($middleware);
29 1
        return $stack;
30
    }
31
32 1
    public function withoutMiddleware(HttpMiddlewareInterface $middleware) : ApplicationStack
33
    {
34 1
        $oldStack = clone $this->stack;
35 1
        $newStack = new \SplStack();
36 1
        while (!$oldStack->isEmpty()) {
37 1
            $middlewareInstance = $oldStack->shift();
38 1
            if ($middlewareInstance !== $middleware) {
39 1
                $newStack->push($middlewareInstance);
40
            }
41
        }
42
43 1
        $stack = clone $this;
44 1
        $stack->stack = $newStack;
45 1
        return $stack;
46
    }
47
48 3
    public function process(ServerRequestInterface $request) : ResponseInterface
49
    {
50 3
        if ($this->stack->count() === 0) {
51 1
            throw new \RuntimeException('Cannot process with an empty stack');
52
        }
53 2
        $stack = clone $this->stack;
54
55
        /** @var  HttpMiddlewareInterface $current */
56 2
        $current = $stack->pop();
57 2
        $response = $current->process($request, new Delegate($stack));
58
59 2
        return $response;
60
    }
61
}
62