Passed
Pull Request — master (#134)
by Rustam
02:33
created

Router::withoutAutoResponseOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Router\Middleware;
6
7
use Psr\Http\Message\ResponseFactoryInterface;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Server\MiddlewareInterface;
11
use Psr\Http\Server\RequestHandlerInterface;
12
use Yiisoft\Http\Method;
13
use Yiisoft\Http\Status;
14
use Yiisoft\Middleware\Dispatcher\MiddlewareDispatcher;
15
use Yiisoft\Router\CurrentRoute;
16
use Yiisoft\Router\CurrentRouteInterface;
17
use Yiisoft\Router\UrlMatcherInterface;
18
19
final class Router implements MiddlewareInterface
20
{
21
    private UrlMatcherInterface $matcher;
22
    private ResponseFactoryInterface $responseFactory;
23
    private MiddlewareDispatcher $dispatcher;
24
    private CurrentRoute $currentRoute;
25
26 9
    public function __construct(
27
        UrlMatcherInterface $matcher,
28
        ResponseFactoryInterface $responseFactory,
29
        MiddlewareDispatcher $dispatcher,
30
        CurrentRouteInterface $currentRoute
31
    ) {
32 9
        $this->matcher = $matcher;
33 9
        $this->responseFactory = $responseFactory;
34 9
        $this->dispatcher = $dispatcher;
35 9
        $this->currentRoute = $currentRoute;
36 9
    }
37
38 9
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
39
    {
40 9
        $result = $this->matcher->match($request);
41
42 9
        $this->currentRoute->setUri($request->getUri());
43
44 9
        if ($result->isMethodFailure()) {
45 3
            if ($request->getMethod() === Method::OPTIONS) {
46 2
                return $this->responseFactory->createResponse(Status::NO_CONTENT)
47 2
                    ->withHeader('Allow', implode(', ', $result->methods()));
48
            }
49 1
            return $this->responseFactory->createResponse(Status::METHOD_NOT_ALLOWED)
50 1
                ->withHeader('Allow', implode(', ', $result->methods()));
51
        }
52
53 6
        if (!$result->isSuccess()) {
54 1
            return $handler->handle($request);
55
        }
56
57 5
        $this->currentRoute->setRoute($result->route());
58 5
        $this->currentRoute->setArguments($result->arguments());
59
60 5
        return $result->withDispatcher($this->dispatcher)->process($request, $handler);
61
    }
62
}
63