Passed
Push — master ( a9f89d...4aed4d )
by Maxime
02:01
created

Router::convertToControllerAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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