Completed
Push — master ( c6f1f9...c5f7f0 )
by Maxime
01:44
created

Router::post()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
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
    /**
40
     * Compare the given request with routes in the routerContainer.
41
     */
42
    public function match(ServerRequestInterface $request): ?Route
43
    {
44
        foreach ($this->routeContainer->getRoutes() as $route) {
45
46
            if ($this->routeContainer->match($request, $route)) {
47
                if (!in_array($request->getMethod(), $route->getAllows())) {
48
                    throw new MethodNotAllowedException($route->getAllows(), $request->getUri()->getPath());
49
                }
50
51
                return $route;
52
            }
53
        }
54
55
        return null;
56
    }
57
    
58
    public function getRoutes()
59
    {
60
        return $this->routeContainer->getRoutes();
61
    }
62
63
    /**
64
     * Create a new route.
65
     *
66
     * @param callable|string $action
67
     */
68
    private function createRoute(string $path, string $name, $action): Route
69
    {
70
        return new Route($path, $name, $action);
71
    }
72
}
73