Passed
Push — master ( 1da3d9...4f22f8 )
by Alexander
23:29 queued 21:59
created

MiddlewareStack   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 95.45%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 59
ccs 21
cts 22
cp 0.9545
rs 10
wmc 3

8 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 7 2
A hp$0 ➔ handle() 0 3 1
A hp$0 ➔ wrap() 0 15 1
A isEmpty() 0 3 1
wrap() 0 15 ?
A build() 0 11 2
A hp$0 ➔ __construct() 0 4 1
A reset() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Router;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\MiddlewareInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
12
final class MiddlewareStack implements MiddlewareStackInterface
13
{
14
    /**
15
     * Contains a stack of middleware wrapped in handlers.
16
     * Each handler points to the handler of middleware that will be processed next.
17
     * @var RequestHandlerInterface|null stack of middleware
18
     */
19
    private ?RequestHandlerInterface $stack = null;
20
21 12
    public function build(array $middlewares, RequestHandlerInterface $fallbackHandler): MiddlewareStackInterface
22
    {
23 12
        $handler = $fallbackHandler;
24 12
        foreach ($middlewares as $middleware) {
25 12
            $handler = $this->wrap($middleware, $handler);
26
        }
27
28 12
        $new = clone $this;
29 12
        $new->stack = $handler;
30
31 12
        return $new;
32
    }
33
34 12
    public function handle(ServerRequestInterface $request): ResponseInterface
35
    {
36 12
        if ($this->isEmpty()) {
37
            throw new \RuntimeException('Stack is empty.');
38
        }
39
40 12
        return $this->stack->handle($request);
41
    }
42
43 12
    public function reset(): void
44
    {
45 12
        $this->stack = null;
46 12
    }
47
48 12
    public function isEmpty(): bool
49
    {
50 12
        return $this->stack === null;
51
    }
52
53
    /**
54
     * Wraps handler by middlewares
55
     */
56 12
    private function wrap(MiddlewareInterface $middleware, RequestHandlerInterface $handler): RequestHandlerInterface
57
    {
58 12
        return new class($middleware, $handler) implements RequestHandlerInterface {
59
            private MiddlewareInterface $middleware;
60
            private RequestHandlerInterface $handler;
61
62
            public function __construct(MiddlewareInterface $middleware, RequestHandlerInterface $handler)
63
            {
64 12
                $this->middleware = $middleware;
65 12
                $this->handler = $handler;
66 12
            }
67
68
            public function handle(ServerRequestInterface $request): ResponseInterface
69
            {
70 12
                return $this->middleware->process($request, $this->handler);
71
            }
72
        };
73
    }
74
}
75