GenericRouter::find()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 3
nop 2
dl 0
loc 15
ccs 10
cts 10
cp 1
crap 3
rs 9.9332
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Igni\Application\Http;
4
5
use Igni\Network\Http\Router;
6
use Igni\Network\Exception\RouterException;
7
use Igni\Network\Http\Route;
8
use Symfony\Component\Routing\Exception\MethodNotAllowedException as SymfonyMethodNotAllowedException;
9
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
10
use Symfony\Component\Routing\Matcher\UrlMatcher;
11
use Symfony\Component\Routing\RequestContext;
12
use Symfony\Component\Routing\Route as SymfonyRoute;
13
use Symfony\Component\Routing\RouteCollection;
14
15
/**
16
 * Wrapper for package symfony/router
17
 *
18
 * @package Igni\Http\Router
19
 */
20
class GenericRouter implements Router
21
{
22
    /** @var RouteCollection */
23
    protected $routeCollection;
24
25
    /** @var Route[] */
26
    protected $routes = [];
27
28 26
    public function __construct()
29
    {
30 26
        $this->routeCollection = new RouteCollection();
31 26
    }
32
33
    /**
34
     * Registers new route.
35
     *
36
     * @param Route $route
37
     */
38 15
    public function add(Route $route): void
39
    {
40 15
        if ($route instanceof Route) {
0 ignored issues
show
introduced by
$route is always a sub-type of Igni\Network\Http\Route.
Loading history...
41 15
            $name = $route->getName();
42
        } else {
43
            $name = Route::generateNameFromPath($route->getPath());
44
        }
45
46 15
        $baseRoute = new SymfonyRoute($route->getPath());
47 15
        $baseRoute->setMethods($route->getMethods());
48
49 15
        $this->routeCollection->add($name, $baseRoute);
50 15
        $this->routes[$name] = $route;
51 15
    }
52
53
    /**
54
     * Finds route matching clients request.
55
     *
56
     * @param string $method request method.
57
     * @param string $path request path.
58
     * @return Route
59
     */
60 17
    public function find(string $method, string $path): Route
61
    {
62 17
        $matcher = new UrlMatcher($this->routeCollection, new RequestContext('/', $method));
63
        try {
64 17
            $route = $matcher->match($path);
65 5
        } catch (ResourceNotFoundException $exception) {
66 4
            throw RouterException::noRouteMatchesRequestedUri($path, $method);
67 1
        } catch (SymfonyMethodNotAllowedException $exception) {
68 1
            throw RouterException::methodNotAllowed($path, $exception->getAllowedMethods());
69
        }
70
71 12
        $routeName = $route['_route'];
72 12
        unset($route['_route']);
73
74 12
        return $this->routes[$routeName]->withAttributes($route);
75
    }
76
}
77