Passed
Push — master ( ecf1a8...0623cd )
by Alexander
15:01 queued 13:39
created

MiddlewareDispatcher   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 90%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 18
c 1
b 0
f 0
dl 0
loc 52
ccs 18
cts 20
cp 0.9
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A hasMiddlewares() 0 3 1
A __construct() 0 4 1
A dispatch() 0 7 2
A withMiddlewares() 0 7 1
A buildMiddlewares() 0 8 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Middleware\Dispatcher;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\RequestHandlerInterface;
10
11
final class MiddlewareDispatcher
12
{
13
    /**
14
     * Contains a stack of middleware handler.
15
     * @var MiddlewareStackInterface stack of middleware
16
     */
17
    private MiddlewareStackInterface $stack;
18
19
    private MiddlewareFactoryInterface $middlewareFactory;
20
21
    /**
22
     * @var callable[]|string[]|array[]
23
     */
24
    private array $middlewareDefinitions = [];
25
26 6
    public function __construct(MiddlewareFactoryInterface $middlewareFactory, MiddlewareStackInterface $stack)
27
    {
28 6
        $this->middlewareFactory = $middlewareFactory;
29 6
        $this->stack = $stack;
30 6
    }
31
32 6
    public function dispatch(ServerRequestInterface $request, RequestHandlerInterface $fallbackHandler): ResponseInterface
33
    {
34 6
        if ($this->stack->isEmpty()) {
35 6
            $this->stack = $this->stack->build($this->buildMiddlewares(), $fallbackHandler);
36
        }
37
38 6
        return $this->stack->handle($request);
39
    }
40
41 6
    public function withMiddlewares(array $middlewareDefinitions): MiddlewareDispatcher
42
    {
43 6
        $clone = clone $this;
44 6
        $clone->middlewareDefinitions = $middlewareDefinitions;
45 6
        $clone->stack->reset();
46
47 6
        return $clone;
48
    }
49
50
    public function hasMiddlewares(): bool
51
    {
52
        return $this->middlewareDefinitions !== [];
53
    }
54
55 6
    private function buildMiddlewares(): array
56
    {
57 6
        $middlewares = [];
58 6
        foreach ($this->middlewareDefinitions as $middlewareDefinition) {
59 6
            $middlewares[] = $this->middlewareFactory->create($middlewareDefinition);
60
        }
61
62 6
        return $middlewares;
63
    }
64
}
65