Passed
Push — master ( 4c7fe9...5fbdf9 )
by Maxime
01:46
created

Router::getRoutes()   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
    public function post(string $path, string $name, $action): Route
33
    {
34
        $route = $this->createRoute($path, $name, $action);
35
        $route->allows('POST');
36
        return $this->routeContainer->addRoute($route);
37
    }
38
39
    public function put(string $path, string $name, $action): Route
40
    {
41
        $route = $this->createRoute($path, $name, $action);
42
        $route->allows('PUT');
43
        return $this->routeContainer->addRoute($route);
44
    }
45
46
    public function delete(string $path, string $name, $action): Route
47
    {
48
        $route = $this->createRoute($path, $name, $action);
49
        $route->allows('DELETE');
50
        return $this->routeContainer->addRoute($route);
51
    }
52
53
    /**
54
     * Compare the given request with routes in the routerContainer.
55
     */
56
    public function match(ServerRequestInterface $request): ?Route
57
    {
58
        foreach ($this->routeContainer->getRoutes() as $route) {
59
60
            if ($this->routeContainer->match($request, $route)) {
61
                if (!in_array($request->getMethod(), $route->getAllows())) {
62
                    throw new MethodNotAllowedException($route->getAllows(), $request->getUri()->getPath());
63
                }
64
65
                return $route;
66
            }
67
        }
68
69
        return null;
70
    }
71
    
72
    public function getRoutes()
73
    {
74
        return $this->routeContainer->getRoutes();
75
    }
76
77
    /**
78
     * Create a new route.
79
     *
80
     * @param callable|string $action
81
     */
82
    private function createRoute(string $path, string $name, $action): Route
83
    {
84
        return new Route($path, $name, $action);
85
    }
86
}
87