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

ApplicationStack   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 2
dl 0
loc 54
ccs 29
cts 29
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 3
A withMiddleware() 0 7 1
A withoutMiddleware() 0 15 3
A process() 0 13 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
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