Completed
Push — master ( 462ba9...3e8ce0 )
by Andrew
08:04 queued 03:25
created

Router::match()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.0119

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
ccs 10
cts 11
cp 0.9091
rs 9.2
cc 4
eloc 9
nc 4
nop 2
crap 4.0119
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(
41 9
                    $route->getMethods(),
42 9
                    $route->getPattern(),
43
                    $key
44
                );
45 4
            }
46 5
        });
47 6
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52 12
    public function match($method, $uri)
53
    {
54 4
        $result = $this->dispatcher->dispatch($method, $uri);
55
56 12
        switch ($result[0]) {
57 12
            case Dispatcher::FOUND:
58 2
                return new Result($this->routes[$result[1]], $result[2]); 
59 6
            case Dispatcher::METHOD_NOT_ALLOWED:
60 1
                throw new MethodNotAllowedException($method, $result[1]);
61 3
            case Dispatcher::NOT_FOUND:
62 1
                throw new NotFoundException($uri);
63
        }
64 4
    }
65
}
66