Completed
Push — master ( 2e923a...169ca3 )
by Dan
05:16
created

Routes::add()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 1
Metric Value
c 3
b 1
f 1
dl 0
loc 27
rs 8.5806
cc 4
eloc 16
nc 8
nop 4
1
<?php
2
3
namespace Ds\Router;
4
5
use Ds\Router\Interfaces\RouteHandlerInterface;
6
use Ds\Router\Interfaces\RoutesInterface;
7
8
/**
9
 * Class Routes
10
 * @package Cyberhut\Route
11
 */
12
class Routes implements RoutesInterface
13
{
14
15
    /**
16
     * List of added routes.
17
     * @var array
18
     */
19
    public $routes = [];
20
21
    private $groupedRoute = false;
22
23
    private $dir = [];
24
25
26
    /**
27
     * Add group of routes
28
     * @param string $path
29
     * @param callable $routeCallback
30
     * @return void
31
     */
32
    public function group($path = '', callable $routeCallback)
33
    {
34
        $this->dir[] = $path;
35
        $this->groupedRoute = true;
36
        $routeCallback();
37
        $this->groupedRoute = false;
38
    }
39
40
    /**
41
     * Add Route to Application.
42
     * @param array|string $method
43
     * @param string $pattern
44
     * @param RouteHandlerInterface $handler
45
     * @param array $name
46
     * @throws \Exception
47
     */
48
    public function add($method, $pattern, RouteHandlerInterface $handler, array $name = ['global'])
49
    {
50
51
        $pattern = ltrim($pattern, '/');
52
        $pattern = '/'.$pattern;
53
54
        if ($this->groupedRoute === false){
55
            $routePattern = $pattern;
56
        }else{
57
            $routePattern = implode('',$this->dir).$pattern;
58
        }
59
60
        $this->isUnique($method, $routePattern);
61
62
        $handler->setName($name);
63
64
        $method = is_array($method) ? $method : [$method];
65
66
        foreach ($method as $httpMethod) {
67
            $this->routes[] = [
68
                'method' => $httpMethod,
69
                'pattern' => $routePattern,
70
                'handler' => $handler,
71
                'name' => $name
72
            ];
73
        }
74
    }
75
76
    /**
77
     * Current added routes
78
     * @return array
79
     */
80
    public function getRoutes()
81
    {
82
        return $this->routes;
83
    }
84
85
    /**
86
     * Check that the Route is unique before adding it (again).
87
     * @param $method
88
     * @param $pattern
89
     * @return bool
90
     * @throws \Exception
91
     */
92
    public function isUnique($method, $pattern)
93
    {
94
        foreach ($this->routes as $route) {
95
            if ($route['pattern'] === $pattern && $route['method'] === $method) {
96
                throw new \Exception('Route has already been added.');
97
            }
98
        }
99
        return true;
100
    }
101
}
102