Completed
Push — master ( 85087e...cd2d6e )
by Sinnarasa
01:58
created

RouteCollection::generateRoutesPath()   F

Complexity

Conditions 23
Paths 408

Size

Total Lines 32
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 2 Features 1
Metric Value
c 2
b 2
f 1
dl 0
loc 32
rs 3.5415
cc 23
eloc 27
nc 408
nop 0

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
     * @var
31
     */
32
    public $matcher;
33
34
    /**
35
     * @param array $routes
36
     * @param array $options
37
     */
38
    public function __construct($routes = null, $options = [])
39
    {
40
        if (!is_null($routes) || !empty($options)) $this->addRoutes($routes, $options);
41
    }
42
43
    /**
44
     * @param array|string $routes
45
     * @param array $options
46
     */
47
    public function addRoutes($routes = null, $options = [])
48
    {
49
        if (!is_null($routes) && !is_array($routes)) {
50
            if (strpos($routes, '.php') === false) $routes = trim($routes, '/') . '/';
51
            if (is_file($routes . '/routes.php') && is_array($routesFile = include $routes . '/routes.php')) $routes = $routesFile;
52
            elseif (is_file($routes) && is_array($routesFile = include $routes)) $routes = $routesFile;
53
            else throw new \InvalidArgumentException('Argument for "' . get_called_class() . '" constructor is not recognized. Expected argument array or file containing array but "' . $routes . '" given');
54
        }
55
        $this->routes['routes_' . $this->countRoutes] = is_array($routes) ? $routes : [];
56
        $this->setRoutes($options, $this->countRoutes);
57
        $this->countRoutes++;
58
    }
59
60
    /**
61
     * @param null $key
62
     * @return array
63
     */
64
    public function getRoutes($key = null)
65
    {
66
        if (!is_null($key))
67
            return isset($this->routes[$key]) ? $this->routes[$key] : '';
68
        return $this->routes;
69
    }
70
71
    /**
72
     * @param $args
73
     */
74
    public function setPrefix($args)
75
    {
76
        if (is_array($args)) {
77
            $nbrArgs = count($args);
78 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...
79
                $this->routes['prefix_' . $i] = '/' . trim($args[$i], '/');
80
        } elseif (is_string($args))
81 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...
82
                $this->routes['prefix_' . $i] = '/' . trim($args, '/');
83
        if ($this->countRoutes == 0) $this->countRoutes++;
84
    }
85
86
    /**
87
     * @param $args
88
     */
89
    public function setOption($args = [])
90
    {
91
        $nbrArgs = count($args);
92
        for ($i = 0; $i < $nbrArgs; ++$i) {
93
            if (is_array($args[$i])) {
94
                $this->setRoutes($args[$i], $i);
95
                if (!isset($this->routes['routes_' . $i])) $this->routes['routes_' . $i] = [];
96
            }
97
        }
98
        if ($this->countRoutes == 0) $this->countRoutes++;
99
    }
100
101
    /**
102
     * @param array $args
103
     * @param $i
104
     */
105
    private function setRoutes($args = [], $i)
106
    {
107
        $this->routes['block_' . $i] = (isset($args['block']) && !empty($args['block'])) ? rtrim($args['block'], '/') . '/' : '';
108
        $this->routes['view_dir_' . $i] = (isset($args['view_dir']) && !empty($args['view_dir'])) ? rtrim($args['view_dir'], '/') . '/' : '';
109
        $this->routes['ctrl_namespace_' . $i] = (isset($args['ctrl_namespace']) && !empty($args['ctrl_namespace'])) ? trim($args['ctrl_namespace'], '\\') . '\\' : '';
110
        $this->routes['prefix_' . $i] = (isset($args['prefix']) && !empty($args['prefix'])) ? '/' . trim($args['prefix'], '/') : '';
111
        $this->routes['subdomain_' . $i] = (isset($args['subdomain'])) ? $args['subdomain'] : '';
112
    }
113
114
    /**
115
     * @param $middleware
116
     * @throws \Exception
117
     */
118
    public function setMiddleware($middleware)
119
    {
120
        if (is_string($middleware)) $middleware = rtrim($middleware, '/');
121
        if (is_array($middleware))
122
            $this->middleware = $middleware;
123
        elseif (is_file($middleware) && is_array($mid = include $middleware))
124
            $this->middleware = $mid;
125
        else throw new \InvalidArgumentException('Accepted argument for setMiddleware are array and array file');
126
    }
127
128
    /**
129
     * @return bool
130
     */
131
    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...
132
    {
133
        $root = ($protocol = (isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] :'http' )) . '://' . ($domain = $_SERVER['SERVER_NAME']) . ((!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 8080) ? ':'.$_SERVER['SERVER_PORT'] : '' ) . str_replace('/index.php', '', $_SERVER['SCRIPT_NAME']);
134
        if (strpos($domain, ($new_domain = $this->getDomain($root))) !== false)
135
            $root = str_replace($domain, $new_domain, $root);
136
        $count = 0;
137
        for ($i = 0; $i < $this->countRoutes; ++$i) {
138
            $prefix = (isset($this->routes['prefix_' . $i])) ? $this->routes['prefix_' . $i] : '';
139
            $subdomain = (isset($this->routes['subdomain_' . $i])) ? $this->routes['subdomain_' . $i] : '';
140
            $url = (!empty($subdomain)) ? str_replace($protocol.'://',$protocol.'://'.$subdomain.'.' ,$root) : $root;
141
            if (isset($this->routes['routes_' . $i]))
142
                foreach ($this->routes['routes_' . $i] as $route => $dependencies) {
143
                    if (is_array($dependencies) && isset($dependencies['use']))
144
                        $use = (is_callable($dependencies['use'])) ? 'closure-' . $count : trim($dependencies['use'], '/');
145
                    elseif (!is_array($dependencies))
146
                        $use = (is_callable($dependencies)) ? 'closure-' . $count : trim($dependencies, '/');
147
                    else
148
                        $use = $route;
149
                    if (isset($route[0]) && $route[0] == '/') {
150
                        (!is_callable($dependencies) && isset($dependencies['name']))
151
                            ? $this->routesByName[$use . '#' . $dependencies['name']] = $url . $prefix . $route
152
                            : $this->routesByName[$use] = $url . $prefix . $route;
153
                    } else {
154
                        (!is_callable($dependencies) && isset($dependencies['name']))
155
                            ? $this->routesByName[$use . '#' . $dependencies['name']] = $protocol . '://' . str_replace('{host}', $new_domain, $route) . $prefix
156
                            : $this->routesByName[$use] = $protocol . '://' . str_replace('{host}', $new_domain, $route) . $prefix;
157
                    }
158
                    $count++;
159
                }
160
        }
161
        return true;
162
    }
163
164
    /**
165
     * @param $url
166
     * @return string
167
     */
168
    public function getDomain($url)
169
    {
170
        $url = parse_url($url);
171
        $domain = $url['host'];
172
        if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
173
            return $regs['domain'];
174
        }
175
        return $domain;
176
    }
177
178
    /**
179
     * @param null $name
180
     * @param array $params
181
     * @param string $subdomain
182
     * @return mixed
183
     */
184
    public function getRoutePath($name, $params = [], $subdomain = '')
185
    {
186
        foreach ($this->routesByName as $key => $route) {
187
            $param = explode('#', $key);
188
            $route = str_replace('{subdomain}', $subdomain, $route);
189
            foreach ($params as $key2 => $value) $route = str_replace(':' . $key2, $value, $route);
190
            if ($param[0] == trim($name, '/')) return $route;
191
            else if (isset($param[1]) && $param[1] == $name) return $route;
192
        }
193
        return null;
194
    }
195
}
196