Passed
Pull Request — master (#124)
by Rustam
02:19
created

Router::withAutoResponseOptions()   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\UrlMatcherInterface;
17
18
final class Router implements MiddlewareInterface
19
{
20
    private UrlMatcherInterface $matcher;
21
    private ResponseFactoryInterface $responseFactory;
22
    private MiddlewareDispatcher $dispatcher;
23
    private CurrentRoute $currentRoute;
24
    private ?bool $autoResponseOptions = false;
25
26 6
    public function __construct(
27
        UrlMatcherInterface $matcher,
28
        ResponseFactoryInterface $responseFactory,
29
        MiddlewareDispatcher $dispatcher,
30
        CurrentRoute $currentRoute
31
    ) {
32 6
        $this->matcher = $matcher;
33 6
        $this->responseFactory = $responseFactory;
34 6
        $this->dispatcher = $dispatcher;
35 6
        $this->currentRoute = $currentRoute;
36 6
    }
37
38 6
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
39
    {
40 6
        $result = $this->matcher->match($request);
41
42 6
        $this->currentRoute->setUri($request->getUri());
43
44 6
        if ($result->isMethodFailure()) {
45 2
            if ($this->autoResponseOptions && $request->getMethod() === Method::OPTIONS) {
46 1
                return $this->responseFactory->createResponse(Status::NO_CONTENT)
47 1
                    ->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 4
        if (!$result->isSuccess()) {
54 1
            return $handler->handle($request);
55
        }
56
57 3
        $this->currentRoute->setRoute($result->route());
58
59 3
        foreach ($result->parameters() as $parameter => $value) {
60 3
            $request = $request->withAttribute($parameter, $value);
61
        }
62
63 3
        return $result->withDispatcher($this->dispatcher)->process($request, $handler);
64
    }
65
66 1
    public function withAutoResponseOptions(): self
67
    {
68 1
        $new = clone $this;
69 1
        $new->autoResponseOptions = true;
70 1
        return $new;
71
    }
72
}
73