Test Failed
Push — master ( 73c405...d57cd2 )
by Konstantins
03:14
created

RouteMatcher   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 76.47%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 9
dl 0
loc 50
ccs 13
cts 17
cp 0.7647
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A match() 0 20 3
1
<?php declare(strict_types = 1);
2
3
namespace Venta\Routing;
4
5
use Psr\Http\Message\ServerRequestInterface;
6
use Venta\Contracts\Routing\FastrouteDispatcherFactory;
7
use Venta\Contracts\Routing\ImmutableRouteCollection as RouteCollectionContract;
8
use Venta\Contracts\Routing\Route as RouteContract;
9
use Venta\Contracts\Routing\RouteMatcher as RouteMatcherContract;
10
use Venta\Contracts\Routing\RouteParser as RouteParserContract;
11
use Venta\Routing\Exception\MethodNotAllowedException;
12
use Venta\Routing\Exception\RouteNotFoundException;
13
14
/**
15
 * Class RouteMatcher
16
 *
17
 * @package Venta\Routing
18
 */
19
final class RouteMatcher implements RouteMatcherContract
20
{
21
22
    /**
23
     * @var FastrouteDispatcherFactory
24
     */
25
    private $fastrouteDispatcherFactory;
26
27
    /**
28
     * @var RouteParserContract
29
     */
30
    private $parser;
31
32
    /**
33
     * RouteMatcher constructor.
34
     *
35
     * @param RouteParserContract $parser
36
     * @param FastrouteDispatcherFactory $fastrouteDispatcherFactory
37
     */
38 2
    public function __construct(RouteParserContract $parser, FastrouteDispatcherFactory $fastrouteDispatcherFactory)
39
    {
40 2
        $this->parser = $parser;
41 2
        $this->fastrouteDispatcherFactory = $fastrouteDispatcherFactory;
42 2
    }
43
44
    /**
45
     * @inheritDoc
46
     */
47 1
    public function match(ServerRequestInterface $request, RouteCollectionContract $routeCollection): RouteContract
48
    {
49 1
        $routes = $routeCollection->all();
50 1
        $parsedRouteData = $this->parser->parse($routes);
51 1
        $dispatcher = $this->fastrouteDispatcherFactory->create($parsedRouteData);
52 1
        $match = $dispatcher->dispatch($request->getMethod(), $request->getUri()->getPath());
53 1
        switch ($match[0]) {
54 1
            case $dispatcher::FOUND:
55
                /** @var RouteContract $route */
56 1
                list(, $route, $variables) = $match;
57
58 1
                return $route->withVariables($variables);
59
            case $dispatcher::METHOD_NOT_ALLOWED:
60
                throw new MethodNotAllowedException($match[1]);
61
            default:
62
                throw new RouteNotFoundException(
63
                    sprintf('Cannot route "%s %s" request.', $request->getMethod(), $request->getUri()->getPath())
64
                );
65
        }
66
    }
67
68
}