Completed
Push — master ( ee0121...2fa707 )
by Sinnarasa
06:26
created

RouteCollection::setRoutes()   C

Complexity

Conditions 10
Paths 512

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 5.7204
cc 10
eloc 6
nc 512
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->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 $middleware
112
     * @throws \Exception
113
     */
114
    public function setMiddleware($middleware)
115
    {
116
        if (is_string($middleware)) $middleware = rtrim($middleware, '/');
117
        if (is_array($middleware))
118
            $this->middleware = $middleware;
119
        elseif (is_file($middleware) && is_array($mid = include $middleware))
120
            $this->middleware = $mid;
121
        else throw new \InvalidArgumentException('Accepted argument for setMiddleware are array and array file');
122
    }
123
124
    /**
125
     * @return bool
126
     */
127
    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...
128
    {
129
        $root = (isset($_SERVER['REQUEST_SCHEME'])?$_SERVER['REQUEST_SCHEME']:'http') . '://' . ($domain = (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'])) . str_replace('/index.php', '', $_SERVER['SCRIPT_NAME']);
130
        if (strpos($domain, ($new_domain = $this->getDomain($root))) !== false)
131
            $root = str_replace($domain, $new_domain, $root);
132
        $count = 0;
133
        for ($i = 0; $i < $this->countRoutes; ++$i) {
134
            $prefix = (isset($this->routes['prefix_' . $i])) ? $this->routes['prefix_' . $i] : '';
135
            if (isset($this->routes['routes_' . $i]))
136
                foreach ($this->routes['routes_' . $i] as $route => $dependencies) {
137
                    if (is_array($dependencies) && isset($dependencies['use']))
138
                        $use = (is_callable($dependencies['use'])) ? 'closure-' . $count : trim($dependencies['use'], '/');
139
                    elseif (!is_array($dependencies))
140
                        $use = (is_callable($dependencies)) ? 'closure-' . $count : trim($dependencies, '/');
141
                    else
142
                        $use = $route;
143
                    if (isset($route[0]) && $route[0] == '/') {
144
                        (!is_callable($dependencies) && isset($dependencies['name'])) ? $this->routesByName[$use . '#' . $dependencies['name']] = $root . $prefix . $route : $this->routesByName[$use] = $root . $prefix . $route;
145
                    } else {
146
                        (!is_callable($dependencies) && isset($dependencies['name'])) ? $this->routesByName[$use . '#' . $dependencies['name']] = $_SERVER['REQUEST_SCHEME'] . '://' . str_replace('{host}', $new_domain, $route) . $prefix : $this->routesByName[$use] = $_SERVER['REQUEST_SCHEME'] . '://' . str_replace('{host}', $new_domain, $route) . $prefix;
147
                    }
148
                    $count++;
149
                }
150
        }
151
        return true;
152
    }
153
154
    /**
155
     * @param $url
156
     * @return bool
157
     */
158
    public function getDomain($url)
159
    {
160
        $url = parse_url($url);
161
        $domain = $url['host'];
162
        if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
163
            return $regs['domain'];
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $regs['domain']; (string) is incompatible with the return type documented by JetFire\Routing\RouteCollection::getDomain of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
164
        }
165
        return $domain;
166
    }
167
168
    /**
169
     * @param null $name
170
     * @param array $params
171
     * @param string $subdomain
172
     * @return mixed
173
     */
174
    public function getRoutePath($name, $params = [], $subdomain = '')
175
    {
176
        foreach ($this->routesByName as $key => $route) {
177
            $param = explode('#', $key);
178
            $route = str_replace('{subdomain}', $subdomain, $route);
179
            foreach ($params as $key2 => $value) $route = str_replace(':' . $key2, $value, $route);
180
            if ($param[0] == trim($name, '/')) return $route;
181
            else if (isset($param[1]) && $param[1] == $name) return $route;
182
        }
183
        return null;
184
    }
185
}
186