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

RouterContainer   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 9
eloc 24
dl 0
loc 70
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A addRoute() 0 14 3
A getRoutes() 0 3 1
A match() 0 13 2
A generatePath() 0 12 3
1
<?php
2
3
namespace Piface\Router;
4
5
use Piface\Router\Exception\DuplicateRouteNameException;
6
use Piface\Router\Exception\DuplicateRouteUriException;
7
use Psr\Http\Message\ServerRequestInterface;
8
9
class RouterContainer
10
{
11
    /**
12
     * Array of route objects
13
     *
14
     * @var Route[]
15
     */
16
    private $routes = [];
17
18
    /**
19
     * index all routes which have been registered to avoid duplication.
20
     *
21
     * @var array
22
     */
23
    private $path = [];
24
25
    public function addRoute(Route $route): Route
26
    {
27
        if (\in_array($route->getPath(), $this->path, true)) {
28
            throw new DuplicateRouteUriException($route->getPath());
29
        }
30
31
        if (array_key_exists($route->getName(), $this->path)) {
32
            throw new DuplicateRouteNameException($route->getName());
33
        }
34
35
        $this->path[$route->getName()] = $route->getPath();
36
        $this->routes[$route->getName()] = $route;
37
38
        return $route;
39
    }
40
41
    /**
42
     * Check if the current object route is matching the request route.
43
     */
44
    public function match(ServerRequestInterface $request, Route $route): bool
45
    {
46
        $requestedPath = $request->getUri()->getPath();
47
        $path = $this->generatePath($route);
48
49
        if (!preg_match("#^$path$#i", $requestedPath, $matches)) {
50
            return false;
51
        }
52
53
        array_shift($matches);
54
        $route->setParameters($matches);
55
56
        return true;
57
    }
58
59
    /**
60
     * @return Route[]
61
     */
62
    public function getRoutes(): array
63
    {
64
        return $this->routes;
65
    }
66
67
    private function generatePath(Route $route): string
68
    {
69
        $path = $route->getPath();
70
71
        if (!empty($route->getWhere())) {
72
            foreach ($route->getWhere() as $attribute => $where) {
73
                $path = preg_replace('#{(' . $attribute . ')}#', '(' . $where . ')', $path);
74
            }
75
        }
76
        $path = preg_replace("#{([\w]+)}#", '([^/]+)', $path);
77
78
        return $path;
79
    }
80
}
81