Passed
Push — master ( 4aed4d...8895e9 )
by Maxime
06:43
created

Router::getAllRoutes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Piface\Router;
4
5
use Piface\Router\Exception\MethodNotAllowedException;
6
use Psr\Http\Message\ServerRequestInterface;
7
8
class Router implements RouterInterface
9
{
10
    /**
11
     * @var RouterContainer
12
     */
13
    private $routeContainer;
14
15
    public function __construct()
16
    {
17
        $this->routeContainer = new RouterContainer();
18
    }
19
20
    /**
21
     * Register a GET route.
22
     *
23
     * @param callable|string $action
24
     */
25
    public function get(string $path, string $name, $action): Route
26
    {
27
        $route = $this->createRoute($path, $name, $action);
28
        $route->allows('GET');
29
        return $this->routeContainer->addRoute($route);
30
    }
31
32
    /**
33
     * Compare the given request with routes in the routerContainer.
34
     */
35
    public function match(ServerRequestInterface $request): ?Route
36
    {
37
        foreach ($this->routeContainer->getRoutes() as $route) {
38
            if ($this->routeContainer->match($request, $route)) {
39
                if (!in_array($request->getMethod(), $route->getAllows())) {
40
                    throw new MethodNotAllowedException($route->getAllows(), $request->getUri()->getPath(), 405);
41
                }
42
43
                return $route;
44
            }
45
        }
46
47
        return null;
48
    }
49
    
50
    public function getRoutes()
51
    {
52
        return $this->routeContainer->getRoutes();
53
    }
54
55
    /**
56
     * Create a new route.
57
     *
58
     * @param callable|string $action
59
     */
60
    private function createRoute(string $path, string $name, $action): Route
61
    {
62
        return new Route($path, $name, $action);
63
    }
64
}
65