ApplicationStack   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 24
dl 0
loc 48
ccs 26
cts 26
cp 1
rs 10
c 3
b 1
f 0
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A process() 0 12 2
A withoutMiddleware() 0 14 3
A withMiddleware() 0 6 1
A __construct() 0 5 2
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