Passed
Pull Request — master (#68)
by Alexander
22:08 queued 07:09
created

MiddlewareStack   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 59
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
    public function build(array $middlewares, RequestHandlerInterface $fallbackHandler): MiddlewareStackInterface
22
    {
23
        $handler = $fallbackHandler;
24
        foreach ($middlewares as $middleware) {
25
            $handler = $this->wrap($middleware, $handler);
26
        }
27
28
        $new = clone $this;
29
        $new->stack = $handler;
30
31
        return $new;
32
    }
33
34
    public function handle(ServerRequestInterface $request): ResponseInterface
35
    {
36
        if ($this->isEmpty()) {
37
            throw new \RuntimeException('Stack is empty.');
38
        }
39
40
        return $this->stack->handle($request);
41
    }
42
43
    public function reset(): void
44
    {
45
        $this->stack = null;
46
    }
47
48
    public function isEmpty(): bool
49
    {
50
        return $this->stack === null;
51
    }
52
53
    /**
54
     * Wraps handler by middlewares
55
     */
56
    private function wrap(MiddlewareInterface $middleware, RequestHandlerInterface $handler): RequestHandlerInterface
57
    {
58
        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
                $this->middleware = $middleware;
65
                $this->handler = $handler;
66
            }
67
68
            public function handle(ServerRequestInterface $request): ResponseInterface
69
            {
70
                return $this->middleware->process($request, $this->handler);
71
            }
72
        };
73
    }
74
}
75