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

MiddlewareStack.php$0 ➔ __construct()   A

Complexity

Conditions 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
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