Completed
Push — master ( 46d40e...8f6f9d )
by Sinnarasa
02:37
created

RouteCollection::addRoutes()   C

Complexity

Conditions 17
Paths 2562

Size

Total Lines 15
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 0 Features 2
Metric Value
c 8
b 0
f 2
dl 0
loc 15
rs 5.221
cc 17
eloc 12
nc 2562
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace JetFire\Routing;
4
5
6
/**
7
 * Class RouteCollection
8
 * @package JetFire\Routing
9
 */
10
class RouteCollection
11
{
12
13
    /**
14
     * @var array
15
     */
16
    private $routes = [];
17
    /**
18
     * @var array
19
     */
20
    public $routesByName = [];
21
    /**
22
     * @var int
23
     */
24
    public $countRoutes = 0;
25
    /**
26
     * @var
27
     */
28
    public $middleware;
29
30
    /**
31
     * @param array $routes
32
     * @param array $options
33
     */
34
    public function __construct($routes = null, $options = [])
35
    {
36
        if (!is_null($routes) || !empty($options)) $this->addRoutes($routes, $options);
37
    }
38
39
    /**
40
     * @param array|string $routes
41
     * @param array $options
42
     */
43
    public function addRoutes($routes = null, $options = [])
44
    {
45
        if(!is_null($routes) && !is_array($routes)) {
46
            if (strpos($routes, '.php') === false) $routes = trim($routes, '/') . '/';
47
            if (is_file($routes . '/routes.php') && is_array($routesFile = include $routes . '/routes.php')) $routes = $routesFile;
48
            elseif (is_file($routes) && is_array($routesFile = include $routes)) $routes = $routesFile;
49
            else throw new \InvalidArgumentException('Argument for "' . get_called_class() . '" constructor is not recognized. Expected argument array or file containing array but "'.$routes.'" given');
50
        }
51
        $this->routes['routes_' . $this->countRoutes] = is_array($routes) ? $routes : [];
52
        $this->routes['view_dir_' . $this->countRoutes] = (isset($options['view_dir']) && !empty($options['view_dir'])) ? rtrim($options['view_dir'], '/') . '/' : '';
53
        $this->routes['block_' . $this->countRoutes] = (isset($options['block']) && !empty($options['block'])) ? rtrim($options['block'], '/') . '/' : $this->routes['view_dir_' . $this->countRoutes];
54
        $this->routes['ctrl_namespace_' . $this->countRoutes] = (isset($options['ctrl_namespace']) && !empty($options['ctrl_namespace'])) ? trim($options['ctrl_namespace'], '\\') . '\\' : '';
55
        $this->routes['prefix_' . $this->countRoutes] = (isset($options['prefix']) && !empty($options['prefix'])) ? '/' . trim($options['prefix'], '/') : '';
56
        $this->countRoutes++;
57
    }
58
59
    /**
60
     * @param null $key
61
     * @return array
62
     */
63
    public function getRoutes($key = null)
64
    {
65
        if(!is_null($key))
66
            return isset($this->routes[$key])?$this->routes[$key]:'';
67
        return $this->routes;
68
    }
69
70
    /**
71
     * @param $args
72
     */
73
    public function setPrefix($args)
74
    {
75
        if (is_array($args)) {
76
            $nbrArgs = count($args);
77 View Code Duplication
            for ($i = 0; $i < $nbrArgs; ++$i)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
78
                $this->routes['prefix_' . $i] = '/' . trim($args[$i], '/');
79
        } elseif (is_string($args))
80 View Code Duplication
            for ($i = 0; $i < $this->countRoutes; ++$i)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
81
                $this->routes['prefix_' . $i] = '/' . trim($args, '/');
82
        if($this->countRoutes == 0)$this->countRoutes++;
83
    }
84
85
    /**
86
     * @param $args
87
     */
88
    public function setOption($args = [])
89
    {
90
        $nbrArgs = count($args);
91
        for ($i = 0; $i < $nbrArgs; ++$i) {
92
            if(is_array($args[$i])){
93
                $this->routes['block_' . $i] = (isset($args[$i]['block']) && !empty($args[$i]['block'])) ? rtrim($args[$i]['block'], '/') . '/' : '';
94
                $this->routes['view_dir_' . $i] = (isset($args[$i]['view_dir']) && !empty($args[$i]['view_dir'])) ? rtrim($args[$i]['view_dir'], '/') . '/' : '';
95
                $this->routes['ctrl_namespace_' . $i] = (isset($args[$i]['ctrl_namespace']) && !empty($args[$i]['ctrl_namespace'])) ? trim($args[$i]['ctrl_namespace'], '\\') . '\\' : '';
96
                $this->routes['prefix_' . $i] = (isset($args[$i]['prefix']) && !empty($args[$i]['prefix'])) ? '/'.trim($args[$i]['prefix'], '/') : '';
97
                if(!isset($this->routes['routes_' . $i]))$this->routes['routes_' . $i] = [];
98
            }
99
        }
100
        if($this->countRoutes == 0)$this->countRoutes++;
101
    }
102
103
    /**
104
     * @param $middleware
105
     * @throws \Exception
106
     */
107
    public function setMiddleware($middleware)
108
    {
109
        if (is_string($middleware)) $middleware = rtrim($middleware, '/');
110
        if(is_array($middleware))
111
            $this->middleware = $middleware;
112
        elseif (is_file($middleware) && is_array($mid = include $middleware))
113
            $this->middleware = $mid;
114
        else throw new \InvalidArgumentException('Accepted argument for setMiddleware are array and array file');
115
    }
116
117
    /**
118
     * @return bool
119
     */
120
    public function generateRoutesPath()
0 ignored issues
show
Coding Style introduced by
generateRoutesPath uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
121
    {
122
        $root = 'http://' . (isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:$_SERVER['SERVER_NAME']) . str_replace('/index.php', '', $_SERVER['SCRIPT_NAME']);
123
        $count = 0;
124
        for ($i = 0; $i < $this->countRoutes; ++$i) {
125
            $prefix = (isset($this->routes['prefix_' . $i])) ? $this->routes['prefix_' . $i] : '';
126
            if (isset($this->routes['routes_' . $i]))
127
                foreach ($this->routes['routes_' . $i] as $route => $dependencies) {
128
                    if (is_array($dependencies) && isset($dependencies['use']))
129
                        $use = (is_callable($dependencies['use'])) ? 'closure-' . $count : trim($dependencies['use'], '/');
130
                    elseif(!is_array($dependencies))
131
                        $use = (is_callable($dependencies)) ? 'closure-' . $count : trim($dependencies, '/');
132
                    else
133
                        $use = $route;
134
                    (!is_callable($dependencies) && isset($dependencies['name'])) ? $this->routesByName[$use . '#' . $dependencies['name']] = $root . $prefix . $route : $this->routesByName[$use] = $root . $prefix . $route;
135
                    $count++;
136
                }
137
        }
138
        return true;
139
    }
140
141
    /**
142
     * @param null $name
143
     * @param array $params
144
     * @return mixed
145
     */
146
    public function getRoutePath($name, $params = [])
147
    {
148
        foreach ($this->routesByName as $key => $route) {
149
            $param = explode('#', $key);
150
            foreach ($params as $key2 => $value) $route = str_replace(':' . $key2, $value, $route);
151
            if ($param[0] == trim($name, '/')) return $route;
152
            else if (isset($param[1]) && $param[1] == $name) return $route;
153
        }
154
        return null;
155
    }
156
}
157