Completed
Push — master ( 0b79b7...fa8b49 )
by Dawid
10s
created

Router   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 49
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A findRoute() 0 15 3
A __construct() 0 3 1
A addRoute() 0 5 1
1
<?php declare(strict_types=1);
2
3
namespace Igni\Http;
4
5
use Igni\Http\Exception\MethodNotAllowedException;
6
use Igni\Http\Exception\NotFoundException;
7
use Symfony\Component\Routing\Exception\MethodNotAllowedException as SymfonyMethodNotAllowedException;
8
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
9
use Symfony\Component\Routing\Matcher\UrlMatcher;
10
use Symfony\Component\Routing\RequestContext;
11
use Symfony\Component\Routing\RouteCollection;
12
13
/**
14
 * Utility class for simplifying api for nikic router.
15
 *
16
 * @package Igni\Http
17
 */
18
class Router
19
{
20
    /**
21
     * @var RouteCollection
22
     */
23
    private $routeCollection;
24
25
    /** @var array */
26
    private $routes = [];
27
28 19
    public function __construct()
29
    {
30 19
        $this->routeCollection = new RouteCollection();
31 19
    }
32
33
    /**
34
     * Registers new route.
35
     *
36
     * @param Route $route
37
     */
38 14
    public function addRoute(Route $route): void
39
    {
40 14
        $baseRoute = $route->getBaseRoute();
41 14
        $this->routeCollection->add($route->getName(), $baseRoute);
42 14
        $this->routes[$route->getName()] = $route;
43 14
    }
44
45
    /**
46
     * Finds route matching clients request.
47
     *
48
     * @param string $method request method.
49
     * @param string $path request path.
50
     * @return Route
51
     */
52 15
    public function findRoute(string $method, string $path): Route
53
    {
54 15
        $matcher = new UrlMatcher($this->routeCollection, new RequestContext('/', $method));
55
        try {
56 15
            $route = $matcher->match($path);
57 4
        } catch (ResourceNotFoundException $exception) {
58 3
            throw NotFoundException::notFound($path, $method);
59 1
        } catch (SymfonyMethodNotAllowedException $exception) {
60 1
            throw MethodNotAllowedException::methodNotAllowed($path, $method, $exception->getAllowedMethods());
61
        }
62
63 11
        $routeName = $route['_route'];
64 11
        unset($route['_route']);
65
66 11
        return $this->routes[$routeName]->withAttributes($route);
67
    }
68
}
69