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

RouteCollection   C

Complexity

Total Complexity 66

Size/Duplication

Total Lines 147
Duplicated Lines 2.72 %

Coupling/Cohesion

Components 2
Dependencies 0

Importance

Changes 11
Bugs 1 Features 2
Metric Value
wmc 66
c 11
b 1
f 2
lcom 2
cbo 0
dl 4
loc 147
rs 5.7474

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 3
C addRoutes() 0 15 17
A getRoutes() 0 6 3
B setPrefix() 4 11 6
C setOption() 0 14 13
B setMiddleware() 0 9 5
B generateRoutesPath() 0 20 13
B getRoutePath() 0 10 6

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like RouteCollection often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use RouteCollection, and based on these observations, apply Extract Interface, too.

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