Passed
Push — master ( c5f7f0...4c7fe9 )
by Maxime
01:42
created

Router::put()   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
    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
    /**
47
     * Compare the given request with routes in the routerContainer.
48
     */
49
    public function match(ServerRequestInterface $request): ?Route
50
    {
51
        foreach ($this->routeContainer->getRoutes() as $route) {
52
53
            if ($this->routeContainer->match($request, $route)) {
54
                if (!in_array($request->getMethod(), $route->getAllows())) {
55
                    throw new MethodNotAllowedException($route->getAllows(), $request->getUri()->getPath());
56
                }
57
58
                return $route;
59
            }
60
        }
61
62
        return null;
63
    }
64
    
65
    public function getRoutes()
66
    {
67
        return $this->routeContainer->getRoutes();
68
    }
69
70
    /**
71
     * Create a new route.
72
     *
73
     * @param callable|string $action
74
     */
75
    private function createRoute(string $path, string $name, $action): Route
76
    {
77
        return new Route($path, $name, $action);
78
    }
79
}
80