Test Failed
Push — master ( 4c92de...3b4c18 )
by Sinnarasa
04:16
created

RouteCollection::setMiddleware()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 7
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
        $this->routes['routes_' . $this->countRoutes] = 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
        if (!is_null($key))
63
            return isset($this->routes[$key]) ? $this->routes[$key] : '';
64
        return $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
    private function setRoutes($args = [], $i)
102
    {
103
        $this->routes['block_' . $i] = (isset($args['block']) && !empty($args['block'])) ? rtrim($args['block'], '/') . '/' : '';
104
        $this->routes['view_dir_' . $i] = (isset($args['view_dir']) && !empty($args['view_dir'])) ? rtrim($args['view_dir'], '/') . '/' : '';
105
        $this->routes['ctrl_namespace_' . $i] = (isset($args['ctrl_namespace']) && !empty($args['ctrl_namespace'])) ? trim($args['ctrl_namespace'], '\\') . '\\' : '';
106
        $this->routes['prefix_' . $i] = (isset($args['prefix']) && !empty($args['prefix'])) ? '/' . trim($args['prefix'], '/') : '';
107
        $this->routes['subdomain_' . $i] = (isset($args['subdomain'])) ? $args['subdomain'] : '';
108
    }
109
110
    /**
111
     * @param string $root
112
     * @param string $script_file
113
     * @return bool
114
     */
115
    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...
116
    {
117
        $protocol = isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http';
118
        $domain = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null;
119
        $root = (is_null($root))
120
            ? $protocol . '://' . $domain . ((!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80) ? ':' . $_SERVER['SERVER_PORT'] : '') . str_replace('/' . $script_file, '', $_SERVER['SCRIPT_NAME'])
121
            : $root;
122
        $new_domain = $this->getDomain($root);
123
        if (!is_null($domain) && strpos($domain, $new_domain) !== false) {
124
            $root = str_replace($domain, $new_domain, $root);
125
        }
126
        $count = 0;
127
        for ($i = 0; $i < $this->countRoutes; ++$i) {
128
            $prefix = (isset($this->routes['prefix_' . $i])) ? $this->routes['prefix_' . $i] : '';
129
            $subdomain = (isset($this->routes['subdomain_' . $i])) ? $this->routes['subdomain_' . $i] : '';
130
            $url = (!empty($subdomain)) ? str_replace($protocol.'://',$protocol.'://'.$subdomain.'.' ,$root) : $root;
131
            if (isset($this->routes['routes_' . $i]))
132
                foreach ($this->routes['routes_' . $i] as $route => $dependencies) {
133
                    if (is_array($dependencies) && isset($dependencies['use']) && !is_array($dependencies['use'])) {
134
                        $use = (is_callable($dependencies['use'])) ? 'closure-' . $count : trim($dependencies['use'], '/');
135
                    } elseif (!is_array($dependencies)) {
136
                        $use = (is_callable($dependencies)) ? 'closure-' . $count : trim($dependencies, '/');
137
                    } else {
138
                        $use = $route;
139
                    }
140
                    if (isset($route[0]) && $route[0] == '/') {
141
                        (!is_callable($dependencies) && isset($dependencies['name']))
142
                            ? $this->routesByName[$use . '#' . $dependencies['name']] = $url . $prefix . $route
143
                            : $this->routesByName[$use] = $url . $prefix . $route;
144
                    } else {
145
                        (!is_callable($dependencies) && isset($dependencies['name']))
146
                            ? $this->routesByName[$use . '#' . $dependencies['name']] = $protocol . '://' . str_replace('{host}', $new_domain, $route) . $prefix
147
                            : $this->routesByName[$use] = $protocol . '://' . str_replace('{host}', $new_domain, $route) . $prefix;
148
                    }
149
                    $count++;
150
                }
151
        }
152
        return true;
153
    }
154
155
    /**
156
     * @param $url
157
     * @return string
158
     */
159
    public function getDomain($url)
160
    {
161
        $url = parse_url($url);
162
        $domain = $url['host'];
163
        if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
164
            return $regs['domain'];
165
        }
166
        return $domain;
167
    }
168
169
    /**
170
     * @param null $name
171
     * @param array $params
172
     * @param string $subdomain
173
     * @return mixed
174
     */
175
    public function getRoutePath($name, $params = [], $subdomain = '')
176
    {
177
        foreach ($this->routesByName as $key => $route) {
178
            $param = explode('#', $key);
179
            $route = str_replace('{subdomain}', $subdomain, $route);
180
            foreach ($params as $key2 => $value) $route = str_replace(':' . $key2, $value, $route);
181
            if ($param[0] == trim($name, '/')) return $route;
182
            else if (isset($param[1]) && $param[1] == $name) return $route;
183
        }
184
        return null;
185
    }
186
}
187