Router   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 19
dl 0
loc 40
ccs 19
cts 19
cp 1
rs 10
c 2
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A process() 0 26 4
A __construct() 0 8 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Router\Middleware;
6
7
use Psr\EventDispatcher\EventDispatcherInterface;
8
use Psr\Http\Message\ResponseFactoryInterface;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use Psr\Http\Server\MiddlewareInterface;
12
use Psr\Http\Server\RequestHandlerInterface;
13
use Yiisoft\Http\Method;
14
use Yiisoft\Http\Status;
15
use Yiisoft\Middleware\Dispatcher\MiddlewareDispatcher;
16
use Yiisoft\Middleware\Dispatcher\MiddlewareFactory;
17
use Yiisoft\Router\CurrentRoute;
18
use Yiisoft\Router\UrlMatcherInterface;
19
20
final class Router implements MiddlewareInterface
21
{
22
    private MiddlewareDispatcher $dispatcher;
23
24 14
    public function __construct(
25
        private UrlMatcherInterface $matcher,
26
        private ResponseFactoryInterface $responseFactory,
27
        MiddlewareFactory $middlewareFactory,
28
        private CurrentRoute $currentRoute,
29
        ?EventDispatcherInterface $eventDispatcher = null
30
    ) {
31 14
        $this->dispatcher = new MiddlewareDispatcher($middlewareFactory, $eventDispatcher);
32
    }
33
34 14
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
35
    {
36 14
        $result = $this->matcher->match($request);
37
38 14
        $this->currentRoute->setUri($request->getUri());
39
40 14
        if ($result->isMethodFailure()) {
41 3
            if ($request->getMethod() === Method::OPTIONS) {
42 2
                return $this->responseFactory
43 2
                    ->createResponse(Status::NO_CONTENT)
44 2
                    ->withHeader('Allow', implode(', ', $result->methods()));
45
            }
46 1
            return $this->responseFactory
47 1
                ->createResponse(Status::METHOD_NOT_ALLOWED)
48 1
                ->withHeader('Allow', implode(', ', $result->methods()));
49
        }
50
51 11
        if (!$result->isSuccess()) {
52 1
            return $handler->handle($request);
53
        }
54
55 10
        $this->currentRoute->setRouteWithArguments($result->route(), $result->arguments());
56
57 10
        return $this->dispatcher
58 10
            ->withMiddlewares($result->route()->getData('enabledMiddlewares'))
59 10
            ->dispatch($request, $handler);
60
    }
61
}
62