Completed
Push — master ( 82399e...557966 )
by Andrew
14:19 queued 10:49
created

Router::match()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.009

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 13
ccs 9
cts 10
cp 0.9
rs 9.4285
cc 3
eloc 8
nc 3
nop 2
crap 3.009
1
<?php
2
3
namespace SimpleRoute;
4
5
use FastRoute;
6
use FastRoute\Dispatcher;
7
use FastRoute\RouteCollector;
8
use SimpleRoute\Exception\MethodNotAllowedException;
9
use SimpleRoute\Exception\NotFoundException;
10
11
final class Router implements RouterInterface
12
{
13
    /**
14
     * @var Dispatcher
15
     */
16
    private $dispatcher;
17
18
    /**
19
     * @var RouteInterface[]
20
     */
21
    private $routes;
22
23
    /**
24
     * @param RouteInterface[] A collection of routes
25
     */
26 15
    public function __construct(array $routes)
27
    {
28 15
        $this->routes = array();
29
30 13
        $this->dispatcher = FastRoute\simpleDispatcher(function (RouteCollector $collector) use ($routes) {
31 5
            foreach ($routes as $route) {
32 12
                if (!$route instanceof RouteInterface) {
33 1
                    throw new \InvalidArgumentException('Routes array must contain only RouteInterface objects');
34
                }
35
36 3
                $key = spl_object_hash($route);
37
38 9
                $this->routes[$key] = $route;
39
40 3
                $collector->addRoute($route->getMethods(), $route->getPattern(), $key);
41 4
            }
42 5
        });
43 6
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48 12
    public function match($method, $uri)
49
    {
50 4
        $routeInfo = $this->dispatcher->dispatch($method, $uri);
51
52 12
        switch ($routeInfo[0]) {
53 12
            case Dispatcher::METHOD_NOT_ALLOWED:
54 1
                throw new MethodNotAllowedException($method, $routeInfo[1]);
55 9
            case Dispatcher::NOT_FOUND:
56 1
                throw new NotFoundException($uri);
57
        }
58
59 2
        return new Result($this->routes[$routeInfo[1]], $routeInfo[2]);
60 4
    }
61
}
62