RouteCollection::setPrefix()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 11
Code Lines 9

Duplication

Lines 4
Ratio 36.36 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 4
loc 11
rs 8.8571
c 1
b 0
f 0
cc 6
eloc 9
nc 6
nop 1
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 $matcher;
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
        $options['routes'] = is_array($routes) ? $routes : [];
52
        $this->setRoutes($options, $this->countRoutes);
53
        $this->countRoutes++;
54
    }
55
56
    /**
57
     * @param null $key
58
     * @return array
59
     */
60
    public function getRoutes($key = null)
61
    {
62
        return (!is_null($key))
63
            ? isset($this->routes[$key]) ? $this->routes[$key] : ''
64
            : $this->routes;
65
    }
66
67
    /**
68
     * @param $args
69
     */
70
    public function setPrefix($args)
71
    {
72
        if (is_array($args)) {
73
            $nbrArgs = count($args);
74 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...
75
                $this->routes['prefix_' . $i] = '/' . trim($args[$i], '/');
76
        } elseif (is_string($args))
77 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...
78
                $this->routes['prefix_' . $i] = '/' . trim($args, '/');
79
        if ($this->countRoutes == 0) $this->countRoutes++;
80
    }
81
82
    /**
83
     * @param $args
84
     */
85
    public function setOption($args = [])
86
    {
87
        $nbrArgs = count($args);
88
        for ($i = 0; $i < $nbrArgs; ++$i) {
89
            if (is_array($args[$i])) {
90
                $this->setRoutes($args[$i], $i);
91
                if (!isset($this->routes['routes_' . $i])) $this->routes['routes_' . $i] = [];
92
            }
93
        }
94
        if ($this->countRoutes == 0) $this->countRoutes++;
95
    }
96
97
    /**
98
     * @param array $args
99
     * @param $i
100
     */
101
    public function setRoutes($args = [], $i)
102
    {
103
        $this->routes['routes_' . $i] = $args['routes'];
104
        $this->routes['block_' . $i] = (isset($args['block']) && !empty($args['block'])) ? rtrim($args['block'], '/') . '/' : '';
105
        $this->routes['view_dir_' . $i] = (isset($args['view_dir']) && !empty($args['view_dir'])) ? $args['view_dir'] : [];
106
        $this->routes['ctrl_namespace_' . $i] = (isset($args['ctrl_namespace']) && !empty($args['ctrl_namespace'])) ? trim($args['ctrl_namespace'], '\\') . '\\' : '';
107
        $this->routes['prefix_' . $i] = (isset($args['prefix']) && !empty($args['prefix'])) ? '/' . trim($args['prefix'], '/') : '';
108
        $this->routes['subdomain_' . $i] = (isset($args['subdomain'])) ? $args['subdomain'] : '';
109
        $this->routes['protocol_' . $i] = (isset($args['protocol'])) ? $args['protocol'] : 'http';
110
        $this->routes['params_' . $i] = (isset($args['params'])) ? $args['params'] : [];
111
    }
112
113
    /**
114
     * @param string $root
115
     * @param string $script_file
116
     * @return bool
117
     */
118
    public function generateRoutesPath($root = null, $script_file = 'index.php')
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...
119
    {
120
        $protocol = isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http';
121
        $domain = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null;
122
123
        if(!is_null($root)){
124
            $protocol = explode('://', $root);
125
            $protocol = $protocol[0];
126
        }else{
127
            $root = $protocol . '://' . $domain . ((!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80) ? ':' . $_SERVER['SERVER_PORT'] : '') . str_replace('/' . $script_file, '', $_SERVER['SCRIPT_NAME']);
128
        }
129
130
        $new_domain = $this->getDomain($root);
131
        if (!is_null($domain) && strpos($domain, $new_domain) !== false) {
132
            $root = str_replace($domain, $new_domain, $root);
133
        }
134
135
        $count = 0;
136
        for ($i = 0; $i < $this->countRoutes; ++$i) {
137
            $prefix = (isset($this->routes['prefix_' . $i])) ? $this->routes['prefix_' . $i] : '';
138
            $subdomain = (isset($this->routes['subdomain_' . $i])) ? $this->routes['subdomain_' . $i] : '';
139
            $block_protocol = (isset($this->routes['protocol_' . $i])) ? $this->routes['protocol_' . $i] : 'http';
140
            $url = (!empty($subdomain)) ? str_replace($protocol . '://', $block_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']) && !is_array($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
                    }
150
                    if (isset($route[0]) && $route[0] == '/') {
151
                        $full_url = rtrim($url, '/') . '/' . trim($prefix, '/') . (empty($prefix) ? '' : '/') . trim($route, '/');
152
                        (!is_callable($dependencies) && isset($dependencies['name']))
153
                            ? $this->routesByName[$use . '#' . $dependencies['name']] = $full_url
154
                            : $this->routesByName[$use] = $full_url;
155
                    } else {
156
                        $full_url = $block_protocol . '://' . str_replace('{host}', $new_domain, $route);
157
                        (!is_callable($dependencies) && isset($dependencies['name']))
158
                            ? $this->routesByName[$use . '#' . $dependencies['name']] = $full_url . $prefix
159
                            : $this->routesByName[$use] = $full_url . $prefix;
160
                    }
161
                    $count++;
162
                }
163
        }
164
        return true;
165
    }
166
167
    /**
168
     * @param $url
169
     * @return string
170
     */
171
    public function getDomain($url)
172
    {
173
        $url = parse_url($url);
174
        $domain = $url['host'];
175
        if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
176
            return $regs['domain'];
177
        }
178
        return $domain;
179
    }
180
181
    /**
182
     * @param null $name
183
     * @param array $params
184
     * @return mixed
185
     */
186
    public function getRoutePath($name, $params = [])
187
    {
188
        foreach ($this->routesByName as $key => $route) {
189
            $param = explode('#', $key);
190
            if(isset($params['{subdomain}'])) $route = str_replace('*', $params['{subdomain}'], $route);
191
            if(isset($params['{method}'])) $route = str_replace('*', $params['{method}'], $route);
192
            foreach ($params as $key2 => $value) $route = str_replace(':' . $key2, $value, $route);
193
            if ($param[0] == trim($name, '/')) return $route;
194
            else if (isset($param[1]) && $param[1] == $name) return $route;
195
        }
196
        return null;
197
    }
198
}
199