Completed
Push — master ( 9056d3...546896 )
by Anderson
01:59
created

Route   D

Complexity

Total Complexity 123

Size/Duplication

Total Lines 938
Duplicated Lines 5.01 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 47
loc 938
rs 4.4444
c 0
b 0
f 0
wmc 123
lcom 1
cbo 0

23 Methods

Rating   Name   Duplication   Size   Complexity  
F add() 12 141 28
A get() 0 4 1
A post() 0 4 1
A put() 0 4 1
A patch() 0 4 1
A delete() 0 4 1
A any() 0 8 2
A matches() 0 10 3
F resource() 35 74 23
D compileRoute() 0 62 11
C register() 0 46 8
F group() 0 68 16
B home() 0 19 5
A auth() 0 16 3
A getRoutes() 0 4 1
A getHiddenRoutes() 0 4 1
A getGroupMiddleware() 0 4 1
A getRouteByName() 0 10 3
D getRouteByPath() 0 43 9
A getHTTPVerbs() 0 4 1
A set404() 0 8 1
A get404() 0 4 1
A setTrasnlateUriDashes() 0 4 1

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 Route 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 Route, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * Route class
5
 *
6
 * @author    Anderson Salas <[email protected]>
7
 * @copyright 2017
8
 * @license   GNU-3.0
9
 *
10
 */
11
12
namespace Luthier\Core;
13
14
class Route
15
{
16
17
    /**
18
     * Supported HTTP Verbs for this class
19
     *
20
     * @var static array $http_verbs Array of supported HTTP Verbs
21
     *
22
     * @access private
23
     */
24
    private static $http_verbs = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'TRACE', 'CONNECT', 'HEAD'];
25
26
    /**
27
     * All improved routes parsed
28
     *
29
     * @var static array $routes Array of routes with meta data
30
     *
31
     * @access private
32
     */
33
    private static $routes = array();
34
35
36
    /**
37
     * CodeIgniter 'default_controller' index of the $route variable in config/routes.php
38
     *
39
     * @var static $defaultController
40
     *
41
     * @access private
42
     */
43
    private static $defaultController;
44
45
46
    /**
47
     * CodeIgniter '404_override' index of the $route variable in config/routes.php
48
     *
49
     * @var static $_404page
50
     *
51
     * @access private
52
     */
53
    private static $_404page = NULL;
54
55
    /**
56
     * CodeIgniter 'translate_uri_dashes' index of the $route variable in config/routes.php
57
     *
58
     * @var static $translateDashes
59
     *
60
     * @access private
61
     */
62
    private static $translateDashes = FALSE;
63
64
    /**
65
     * Array of hidden routes, it will parsed as an route with a show_404() callback into a clousure
66
     *
67
     * @var static $hiddenRoutes
68
     *
69
     * @access private
70
     */
71
    private static $hiddenRoutes = array();
72
73
    /**
74
     * (For route groups only) makes the 'hideOriginal' attribute global for the current group
75
     *
76
     * @var static $hideOriginals
77
     *
78
     * @access private
79
     */
80
    private static $hideOriginals = FALSE;
81
82
    /**
83
     * (For route groups only) makes the 'prefix' attribute global for the current group
84
     *
85
     * @var static $prefix
86
     *
87
     * @access private
88
     */
89
    private static $prefix = NULL;
90
91
    /**
92
     * (For route groups only) makes the 'namespace' attribute global for the current group
93
     *
94
     * @var static $namespace
95
     *
96
     * @access private
97
     */
98
    private static $namespace = NULL;
99
100
    /**
101
     * (For route groups only) makes the 'middleware' attribute global for the current group
102
     *
103
     * @var static $middleware
104
     *
105
     * @access private
106
     */
107
    private static $middleware = array();
108
109
    /**
110
     * Array with group middleware. It will be used with the Middleware class as a global route filter
111
     *
112
     * @var static $groupMiddleware
113
     *
114
     * @access private
115
     */
116
    private static $groupMiddleware = array();
117
118
    /**
119
     * Generic method to add a improved route
120
     *
121
     * @param  mixed $verb String or array of string of valid HTTP Verbs that will be accepted in this route
122
     * @param  mixed $url String or array of strings that will trigger this route
0 ignored issues
show
Bug introduced by
There is no parameter named $url. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
123
     * @param  array $attr Associative array of route attributes
124
     * @param  bool $hideOriginal (Optional) map the original $url as a route with a show_404() callback inside
125
     *
126
     * @return void
127
     *
128
     * @access public
129
     * @static
130
     */
131
    public static function add($verb, $path, $attr, $hideOriginal = TRUE, $return = FALSE)
132
    {
133
        if(!is_array($attr))
134
        {
135
            show_error('You must specify the route attributes as an array',500,'Route error: bad attributes');
136
        }
137
138
        if(!isset($attr['uses']))
139
        {
140
            show_error('Route requires a \'controller@method\' to be pointed and it\'s not defined in the route attributes', 500, 'Route error: missing controller');
141
        }
142
143
        if(!preg_match('/^([a-zA-Z1-9-_]+)@([a-zA-Z1-9-_]+)$/', $attr['uses'], $parsedController) !== FALSE)
144
        {
145
            show_error('Route controller must be in format controller@method', 500, 'Route error: bad controller format');
146
        }
147
148
        $controller = $parsedController[1];
149
        $method     = $parsedController[2];
150
151
        if(!is_string($path))
152
            show_error('Route path must be a string ', 500, 'Route error: bad route path');
153
154
        if(!is_string($verb))
155
            show_error('Route HTTP Verb must be a string', 500, 'Route error: bad verb type');
156
157
        $verb = strtoupper($verb);
158
159
        if(!in_array($verb, self::$http_verbs,TRUE))
160
        {
161
            $errorMsg = 'Verb "'.$verb.'" is not a valid HTTP Verb, allowed verbs:<ul>';
162
            foreach( self::$http_verbs as $validVerb )
0 ignored issues
show
Bug introduced by
The expression self::$http_verbs of type object<Luthier\Core\Route> is not traversable.
Loading history...
163
            {
164
                $errorMsg .= '<li>'.$validVerb.'</li>';
165
            }
166
            $errorMsg .= '</ul>';
167
            show_error($errorMsg,500,'Route error: unknow method');
168
        }
169
170
        $route['verb'] = $verb;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$route was never initialized. Although not strictly required by PHP, it is generally a good practice to add $route = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
171
172
        $path = trim($path,'/');
173
174
        //if($path == '')
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
175
        //    $path = '/';
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
176
177
        $route['path']       = $path;
178
        $route['controller'] = $controller;
179
        $route['method']     = $method;
180
181
        if(isset($attr['as']))
182
        {
183
            $route['name'] = $attr['as'];
184
        }
185
        else
186
        {
187
            $route['name'] = NULL;
188
        }
189
190
        $route['prefix'] = NULL;
191
192
        if(!is_null(self::$prefix))
193
            $route['prefix'] = self::$prefix;   # Group
194
        if(isset($attr['prefix']))
195
            $route['prefix'] = $attr['prefix']; # Specific (will overwrite group prefix)
196
197
        $route['namespace'] = NULL;
198
199
        if(!is_null(self::$namespace))
200
            $route['namespace'] = self::$namespace;   # Group
201
        if(isset($attr['namespace']))
202
            $route['namespace'] = $attr['namespace']; # Specific (will overwrite group namespace)
203
204
        # Removing trailing slashes
205 View Code Duplication
        if(!is_null($route['prefix']))
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...
206
        {
207
            $route['prefix'] = trim($route['prefix'],'/');
208
            if($route['prefix'] == '')
209
                $route['prefix'] = NULL;
210
        }
211 View Code Duplication
        if(!is_null($route['namespace']))
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...
212
        {
213
            $route['namespace'] = trim($route['namespace'],'/');
214
            if($route['namespace'] == '')
215
                $route['namespace'] = NULL;
216
        }
217
218
        $route['middleware'] = array();
219
220
        if(isset($attr['middleware']))
221
        {
222
            if(is_array($attr['middleware']))
223
            {
224
                foreach($attr['middleware'] as $middleware)
225
                    $route['middleware'][] = $middleware; # Group
226
            }
227
            elseif( is_string($attr['middleware']))
228
            {
229
                $route['middleware'][] = $attr['middleware']; # Group
230
            }
231
            else
232
            {
233
                show_error('Route middleware must be a string or an array',500,'Route error: bad middleware format');
234
            }
235
        }
236
237
        $compiledRoute = self::compileRoute((object) $route);
238
239
        $route['compiled'] = [
240
            $compiledRoute->path => $compiledRoute->route
241
        ];
242
243
        if($hideOriginal || self::$hideOriginals === TRUE || ($compiledRoute->path != '' && $compiledRoute->path != '/' ) )
244
        {
245
            $hiddenRoutePath      = $controller.'/'.$method;
246
            $hiddenRouteNamespace = '';
247
248
            if(!is_null($route['namespace']))
249
            {
250
                $hiddenRouteNamespace = $route['namespace'].'/';
251
            }
252
253
            $hiddenRoutePath = $hiddenRouteNamespace.$hiddenRoutePath;
254
255
            if($method == 'index')
256
            {
257
                self::$hiddenRoutes[] = [ $hiddenRouteNamespace.$controller  => function(){ show_404(); }];
258
            }
259
260
            self::$hiddenRoutes[] = [$hiddenRoutePath => function(){ show_404(); }];
261
        }
262
263
        if(!$return)
264
        {
265
            self::$routes[] = (object) $route;
266
        }
267
        else
268
        {
269
            return (object) $route;
270
        }
271
    }
272
273
    /**
274
     * Adds a GET route, alias of Route::add('GET',$url,$attr,$hideOriginal)
275
     *
276
     * @param  mixed $url String or array of strings that will trigger this route
277
     * @param  array $attr Associative array of route attributes
278
     * @param  bool $hideOriginal (Optional) map the original $url as a route with a show_404() callback inside
279
     *
280
     * @return void
281
     *
282
     * @access public
283
     * @static
284
     */
285
    public static function get($url, $attr, $hideOriginal = TRUE)
286
    {
287
        self::add('GET', $url,$attr, $hideOriginal);
288
    }
289
290
    /**
291
     * Adds a POST route, alias of Route::add('POST',$url,$attr,$hideOriginal)
292
     *
293
     * @param  mixed $url String or array of strings that will trigger this route
294
     * @param  array $attr Associative array of route attributes
295
     * @param  bool $hideOriginal (Optional) map the original $url as a route with a show_404() callback inside
296
     *
297
     * @return void
298
     *
299
     * @access public
300
     * @static
301
     */
302
    public static function post($url, $attr, $hideOriginal = TRUE)
303
    {
304
        self::add('POST', $url,$attr, $hideOriginal);
305
    }
306
307
    /**
308
     * Adds a PUT route, alias of Route::add('PUT',$url,$attr,$hideOriginal)
309
     *
310
     * @param  mixed $url String or array of strings that will trigger this route
311
     * @param  array $attr Associative array of route attributes
312
     * @param  bool $hideOriginal (Optional) map the original $url as a route with a show_404() callback inside
313
     *
314
     * @return void
315
     *
316
     * @access public
317
     * @static
318
     */
319
    public static function put($url, $attr, $hideOriginal = TRUE)
320
    {
321
        self::add('PUT', $url,$attr, $hideOriginal);
322
    }
323
324
    /**
325
     * Adds a PATCH route, alias of Route::add('PATCH',$url,$attr,$hideOriginal)
326
     *
327
     * @param  mixed $url String or array of strings that will trigger this route
328
     * @param  array $attr Associative array of route attributes
329
     * @param  bool $hideOriginal (Optional) map the original $url as a route with a show_404() callback inside
330
     *
331
     * @return void
332
     *
333
     * @access public
334
     * @static
335
     */
336
    public static function patch($url, $attr, $hideOriginal = TRUE)
337
    {
338
        self::add('PATCH', $url,$attr, $hideOriginal);
339
    }
340
341
    /**
342
     * Adds a DELETE route, alias of Route::add('DELETE',$url,$attr,$hideOriginal)
343
     *
344
     * @param  mixed $url String or array of strings that will trigger this route
345
     * @param  array $attr Associative array of route attributes
346
     * @param  bool $hideOriginal (Optional) map the original $url as a route with a show_404() callback inside
347
     *
348
     * @return void
349
     *
350
     * @access public
351
     * @static
352
     */
353
    public static function delete($url, $attr, $hideOriginal = TRUE)
354
    {
355
        self::add('DELETE', $url,$attr, $hideOriginal);
356
    }
357
358
    /**
359
     * Adds a route with ALL accepted verbs on Route::$http_verbs
360
     *
361
     * @param  mixed $url String or array of strings that will trigger this route
362
     * @param  array $attr Associative array of route attributes
363
     * @param  bool $hideOriginal (Optional) map the original $url as a route with a show_404() callback inside
364
     *
365
     * @return void
366
     *
367
     * @access public
368
     * @static
369
     */
370
    public static function any($url, $attr, $hideOriginal = TRUE)
371
    {
372
        foreach(self::$http_verbs as $verb)
0 ignored issues
show
Bug introduced by
The expression self::$http_verbs of type object<Luthier\Core\Route> is not traversable.
Loading history...
373
        {
374
            $verb = strtolower($verb);
375
            self::add($verb, $url, $attr, $hideOriginal);
376
        }
377
    }
378
379
    /**
380
     * Adds a list of routes with the verbs contained in $verbs, alias of Route::add($verbs,$url,$attr,$hideOriginal)
381
     *
382
     * @param  mixed $verb String or array of string of valid HTTP Verbs that will be accepted in this route
0 ignored issues
show
Bug introduced by
There is no parameter named $verb. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
383
     * @param  mixed $url String or array of strings that will trigger this route
384
     * @param  array $attr Associative array of route attributes
385
     * @param  bool $hideOriginal (Optional) map the original $url as a route with a show_404() callback inside
386
     *
387
     * @return void
388
     *
389
     * @access public
390
     * @static
391
     */
392
    public static function matches($verbs, $url, $attr, $hideOriginal = FALSE)
393
    {
394
        if(!is_array($verbs))
395
            show_error('Route::matches() first argument must be an array of valid HTTP Verbs', 500, 'Route error: bad Route::matches() verb list');
396
397
        foreach($verbs as $verb)
398
        {
399
            self::add($verb, $url, $attr, $hideOriginal);
400
        }
401
    }
402
403
    /**
404
     * Adds a RESTFul route wich contains methods for create, read, update, view an specific resource
405
     *
406
     * This is a shorthand of creating
407
     *      Route::get('{{url}}',['uses' => '{controller}@index', 'as' => '{controller}.index']);
408
     *      Route::get('{{url}}/create',['uses' => '{controller}@create', 'as' => '{controller}.create']);
409
     *      Route::post('{{url}}',['uses' => '{controller}@store', 'as' => '{controller}.store']);
410
     *      Route::get('{{url}}/{slug}',['uses' => '{controller}@show', 'as' => '{controller}.show']);
411
     *      Route::get('{{url}}/edit',['uses' => '{controller}@edit', 'as' => '{controller}.edit']);
412
     *      Route::matches(['PUT','PATCH'],'{{url}}/{slug}',['uses' => '{controller}@update', 'as' => '{controller}.update']);
413
     *      Route::delete('{{url}}/{slug}',['uses' => '{controller}@delete', 'as' => '{controller}.delete']);
414
     *
415
     * PLEASE NOTE: This is NOT a crud generator, just a bundle of predefined routes.
416
     *
417
     * @param  string $url String or array of strings that will trigger this route
0 ignored issues
show
Bug introduced by
There is no parameter named $url. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
418
     * @param  string $controller Controller name (only controller name)
419
     * @param  array $attr Associative array of route attributes
420
     *
421
     * @return void
422
     *
423
     * @access public
424
     * @static
425
     */
426
    public static function resource($name, $controller, $attr = NULL)
427
    {
428
        $base_attr = array();
429
430
        $hideOriginal = FALSE;
431
432
        if(isset($attr['namespace']))
433
            $base_attr['namespace']  = $attr['namespace'];
434
435
        if(isset($attr['middleware']))
436
            $base_attr['middleware'] = $attr['middleware'];
437
438
        if(isset($attr['hideOriginal']))
439
            $hideOriginal = (bool) $attr['hideOriginal'];
440
441
        if(isset($attr['prefix']))
442
            $base_attr['prefix']  = $attr['prefix'];
443
444
        $only = array();
445
446
        if(isset($attr['only']) && (is_array($attr['only']) || is_string($attr['only'])))
447
        {
448
            if(is_array($attr['only']))
449
            {
450
                $only  = strtolower($attr['only']);
451
            }
452
            else
453
            {
454
                $only[] = strtolower($attr['only']);
455
            }
456
        }
457
458 View Code Duplication
        if(empty($only) || in_array('index', $only))
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...
459
        {
460
            $route_attr = array_merge($base_attr, ['uses' => $controller.'@index',   'as' => $name.'.index']);
461
            self::get('/', $route_attr, $hideOriginal);
462
        }
463
464 View Code Duplication
        if(empty($only) || in_array('create', $only))
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...
465
        {
466
            $route_attr = array_merge($base_attr, ['uses' => $controller.'@create', 'as' => $name.'.create']);
467
            self::get('create', $route_attr, $hideOriginal);
468
        }
469
470 View Code Duplication
        if(empty($only) || in_array('store', $only))
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...
471
        {
472
            $route_attr = array_merge($base_attr, ['uses' => $controller.'@store', 'as' => $name.'.store']);
473
            self::post('/', $route_attr, $hideOriginal);
474
        }
475
476 View Code Duplication
        if(empty($only) || in_array('show', $only))
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...
477
        {
478
            $route_attr = array_merge($base_attr, ['uses' => $controller.'@show', 'as' => $name.'.show']);
479
            self::get('{slug}', $route_attr, $hideOriginal);
480
        }
481
482 View Code Duplication
        if(empty($only) || in_array('edit', $only))
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...
483
        {
484
            $route_attr = array_merge($base_attr, ['uses' => $controller.'@edit', 'as' => $name.'.edit']);
485
            self::get('{slug}/edit', $route_attr, $hideOriginal);
486
        }
487
488 View Code Duplication
        if(empty($only) || in_array('update', $only))
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...
489
        {
490
            $route_attr = array_merge($base_attr, ['uses' => $controller.'@update', 'as' => $name.'.update']);
491
            self::matches(['PUT', 'PATCH'], '{slug}/update', $route_attr, $hideOriginal);
492
        }
493
494 View Code Duplication
        if(empty($only) || in_array('destroy', $only))
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...
495
        {
496
            $route_attr = array_merge($base_attr, ['uses' => $controller.'@destroy', 'as' => $name.'.destroy']);
497
            self::delete('{slug}', $route_attr, $hideOriginal);
498
        }
499
    }
500
501
    /**
502
     * Compiles an improved route to a valid CodeIgniter route
503
     *
504
     * @param  array $route an improved route
505
     *
506
     * @return array
507
     *
508
     * @access public
509
     * @static
510
     */
511
    public static function compileRoute($route)
512
    {
513
        $prefix    = NULL;
514
        $namespace = NULL;
515
516
        if(!is_null($route->prefix))
517
        {
518
            $prefix = $route->prefix;
519
        }
520
521
        if(!is_null($route->namespace))
522
        {
523
            $namespace = $route->namespace;
524
        }
525
526
        $path = $route->path;
527
528
        if(!is_null($prefix))
529
            $path = $prefix.'/'.$path;
530
531
        if(substr($path, 0, 1) == "/" && strlen($path) > 1)
532
            $path = substr($path,1);
533
534
        $controller = $route->controller.'/'.$route->method;
535
536
        if(!is_null($namespace))
537
            $controller = $namespace.'/'.$controller;
538
539
        $replaces =
540
            [
541
                '{\((.*)\):[a-zA-Z0-9-_]*}' => '($1)',   # Custom regular expression
542
                '{num:[a-zA-Z0-9-_]*}'      => '(:num)', # (:num) route
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
543
                '{any:[a-zA-Z0-9-_]*}'      => '(:any)', # (:any) route
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
544
                '{[a-zA-Z0-9-_]*}'          => '(:any)', # Everything else
545
            ];
546
547
        $argCount = 0;
548
549
        foreach($replaces as $regex => $replace)
550
        {
551
            $path = preg_replace('/'.$regex.'/', $replace, $path, -1, $argCount);
552
        }
553
554
        if($argCount > 0)
555
        {
556
            for($i = 0; $i < $argCount; $i++)
557
            {
558
                $controller .= '/$'.($i + 1);
559
            }
560
        }
561
562
        // Removing trailing slash (it causes 404 even if the route exists, I don't know why)
563
        if(substr($path,-1) == '/')
564
        {
565
            $path = substr($path,0,-1);
566
        }
567
568
        return (object) [
569
            'path'  => $path,
570
            'route' => $controller,
571
        ];
572
    }
573
574
    /**
575
     * Compile ALL improved routes into a valid CodeIgniter's associative array of routes
576
     *
577
     * @return array
578
     *
579
     * @access public
580
     * @static
581
     */
582
    public static function register()
583
    {
584
        $routes = array();
585
586
        foreach(self::$routes as $index => $route)
0 ignored issues
show
Bug introduced by
The expression self::$routes of type object<Luthier\Core\Route> is not traversable.
Loading history...
587
        {
588
            $compiled = self::compileRoute($route);
589
590
            if( !isset($routes[$compiled->path]) || $route->verb == 'GET' )
591
            {
592
                $routes[$compiled->path] = $compiled->route;
593
            }
594
595
            self::$routes[$index] = (object) $route;
596
        }
597
598
        foreach(self::$hiddenRoutes as $route)
0 ignored issues
show
Bug introduced by
The expression self::$hiddenRoutes of type object<Luthier\Core\Route> is not traversable.
Loading history...
599
        {
600
            $path = key($route);
601
            $_404 = $route[$path];
602
603
            if(!isset($routes[$path]))
604
                $routes[$path] = $_404;
605
        }
606
607
        if(is_null(self::$defaultController))
608
            show_error('You must specify a home route: Route::home() as default controller!', 500, 'Route error: missing default controller');
609
610
        $defaultController = self::$defaultController->compiled;
0 ignored issues
show
Bug introduced by
The property compiled does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
611
        $defaultController = $defaultController[key($defaultController)];
612
613
        $routes['default_controller'] = $defaultController;
614
615
        if(is_null(self::$_404page))
616
        {
617
            $routes['404_override'] = '';
618
        }
619
        else
620
        {
621
            $routes['404_override'] = self::$_404page->controller;
0 ignored issues
show
Bug introduced by
The property controller does not seem to exist. Did you mean defaultController?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
622
        }
623
624
        $routes['translate_uri_dashes'] = self::$translateDashes;
625
626
        return $routes;
627
    }
628
629
    /**
630
     * Creates a group of routes with common attributes
631
     *
632
     * @param  array $attr set of global attributes
633
     * @param  callback $routes wich contains a set of Route methods
634
     *
635
     * @return void
636
     *
637
     * @access public
638
     * @static
639
     */
640
    public static function group($attr, $routes)
641
    {
642
        if(!is_array($attr))
643
            show_error('Group attribute must be a valid array');
644
645
        if(!isset($attr['prefix']))
646
            show_error('You must specify an prefix!');
647
648
        self::$prefix = $attr['prefix'];
649
650
        if(isset($attr['namespace']))
651
        {
652
            self::$namespace = $attr['namespace'];
653
        }
654
655
        if(isset($attr['hideOriginals']) && $attr['hideOriginals'] === TRUE)
656
        {
657
            self::$hideOriginals = TRUE;
0 ignored issues
show
Documentation Bug introduced by
It seems like TRUE of type boolean is incompatible with the declared type object<Luthier\Core\Route> of property $hideOriginals.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
658
        }
659
        else
660
        {
661
            self::$hideOriginals = FALSE;
0 ignored issues
show
Documentation Bug introduced by
It seems like FALSE of type false is incompatible with the declared type object<Luthier\Core\Route> of property $hideOriginals.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
662
        }
663
664
        if(isset($attr['middleware']))
665
        {
666
            if(is_array($attr['middleware']) || is_string($attr['middleware']))
667
            {
668
                //self::$middleware = $attr['middleware'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
669
                if(is_array($attr['middleware']) && !empty($attr['middleware']))
670
                {
671
                    foreach($attr['middleware'] as $middleware)
672
                        self::$groupMiddleware[] = [ $attr['prefix'] => $middleware ];
673
                }
674
                else
675
                {
676
                    self::$groupMiddleware[] = [ $attr['prefix'] => $attr['middleware'] ];
677
                }
678
            }
679
            else
680
            {
681
                show_error('Group middleware not valid');
682
            }
683
        }
684
685
        # Special workarround for default group controller:
686
        # Probably i'll remove it.
687
        if(isset($attr['default']))
688
        {
689
            $url = str_ireplace('@', '/', $attr['default']);
0 ignored issues
show
Unused Code introduced by
$url is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
690
            $uri = explode('/',$attr['default']);
691
            $controller = $uri[0];
692
            $method = isset($uri[1]) ? $uri[1] : NULL;
693
694
            if(self::$hideOriginals === TRUE)
695
                self::$hiddenRoutes[] = [$controller => function(){ show_404(); }];
696
697
            $route_attr['uses'] = $controller.( !is_null($method) ? '/'.$method : '');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$route_attr was never initialized. Although not strictly required by PHP, it is generally a good practice to add $route_attr = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
698
            self::get('/', $route_attr);
699
        }
700
701
        $res = $routes->__invoke();
0 ignored issues
show
Bug introduced by
The method __invoke cannot be called on $routes (of type callable).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
Unused Code introduced by
$res is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
702
703
        self::$prefix     = NULL;
704
        self::$namespace  = NULL;
705
        self::$middleware    = NULL;
706
        self::$hideOriginals = FALSE;
0 ignored issues
show
Documentation Bug introduced by
It seems like FALSE of type false is incompatible with the declared type object<Luthier\Core\Route> of property $hideOriginals.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
707
    }
708
709
    /**
710
     * Creates the 'default_controller' key in CodeIgniter's route array
711
     *
712
     * @param  string $route controller/method name
0 ignored issues
show
Bug introduced by
There is no parameter named $route. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
713
     * @param  string $alias (Optional) alias of the default controller
0 ignored issues
show
Bug introduced by
There is no parameter named $alias. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
714
     *
715
     * Due a CodeIgniter limitations, this route MAY NOT be a directory.
716
     *
717
     * @return void
718
     *
719
     * @access public
720
     * @static
721
     */
722
    public static function home($controller, $as = 'home', $attr = NULL)
723
    {
724
        $routeAttr =
725
            [
726
                'uses' => $controller,
727
                'as'   => $as
728
            ];
729
730
        if(!is_null($attr) && !is_array($attr))
731
            show_error('Default controller attributes must be an array',500,'Route error: bad attribute type');
732
733
        if(!is_null($attr))
734
            $routeAttr = array_merge($routeAttr,$attr);
0 ignored issues
show
Unused Code introduced by
$routeAttr is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
735
736
        if(isset($attr['prefix']))
737
            show_error('Default controller may not have a prefix!',500,'Route error: prefix not allowed');
738
739
        self::$defaultController = self::$routes[] = self::add('GET', '/', ['uses' => $controller, 'as' => $as],TRUE, TRUE);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to self::$routes[] is correct as self::add('GET', '/', ar...s' => $as), TRUE, TRUE) (which targets Luthier\Core\Route::add()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
740
    }
741
742
    /**
743
     * Create the Auth's routes
744
     *
745
     * @param  $attr (Optional) route attributes
746
     *
747
     * @return void
748
     *
749
     * @access public
750
     * @static
751
     */
752
    public static function auth($controller = 'auth', $attr = NULL)
753
    {
754
        $baseAttr['prefix']     = 'auth';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$baseAttr was never initialized. Although not strictly required by PHP, it is generally a good practice to add $baseAttr = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
755
        $baseAttr['middleware'] = 'Auth';
756
757
        if(!is_null($attr) && is_array($attr))
758
        {
759
            $baseAttr = array_merge($baseAttr, $attr);
760
        }
761
762
        self::group($baseAttr, function() use($controller)
763
        {
764
            self::matches(['get','post'], '/login',  ['uses' => $controller.'@login',  'as' => $controller.'.login']);
765
            self::get('/logout', ['uses' => $controller.'@logout', 'as' => $controller.'.logout']);
766
        });
767
    }
768
769
770
    /**
771
     * Get all the improved routes defined
772
     *
773
     * @return array List of all defined routes
774
     *
775
     * @access public
776
     * @static
777
     */
778
    public static function getRoutes()
779
    {
780
        return self::$routes;
781
    }
782
783
    /**
784
     * Get all hidden routes
785
     *
786
     * @return array
787
     *
788
     * @access public
789
     * @static
790
     */
791
    public static function getHiddenRoutes()
792
    {
793
        return self::$hiddenRoutes;
794
    }
795
796
    /**
797
     * Get all middleware defined by route groups.
798
     *
799
     * This middleware actually works as uri filter since they will not check the route,
800
     * just check if the current uri string matches the prefix of the route group.
801
     *
802
     * @return array
803
     *
804
     * @access public
805
     * @static
806
     */
807
    public static function getGroupMiddleware()
808
    {
809
        return self::$groupMiddleware;
810
    }
811
812
    /**
813
     * Retrieve a route wich is called $search (if exists)
814
     *
815
     * @param  string $search The route name to search
816
     * @param  $args (Optional) The route arguments that will be parsed
817
     *
818
     * @return mixed Founded route in case of success, and error in case of no matches.
819
     *
820
     * @access public
821
     * @static
822
     */
823
    public static function getRouteByName($search, $args = NULL)
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
824
    {
825
        foreach(self::$routes as $route)
0 ignored issues
show
Bug introduced by
The expression self::$routes of type object<Luthier\Core\Route> is not traversable.
Loading history...
826
        {
827
            if($route->name == $search)
828
                return base_url(self::compileRoute($route)->path);
829
        }
830
831
        show_error('The route "'.$search.'" is not defined', 500, 'Route error');
832
    }
833
834
    /**
835
     *  Heuristic comprobation of current uri_string in compiled routes
836
     *
837
     *  This is the 'reverse' process of the improved routing, it'll take the current
838
     *  uri string and attempts to find a CodeIgniter route that matches with his pattern
839
     *
840
     * @param  string $search The current uri string
0 ignored issues
show
Bug introduced by
There is no parameter named $search. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
841
     *
842
     * @return mixed
843
     */
844
    public static function getRouteByPath($path, $requestMethod = NULL)
0 ignored issues
show
Coding Style introduced by
getRouteByPath 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...
845
    {
846
        $routes = array();
847
848
        foreach(self::$routes as $route)
0 ignored issues
show
Bug introduced by
The expression self::$routes of type object<Luthier\Core\Route> is not traversable.
Loading history...
849
        {
850
            $routes[$route->verb][] = $route;
851
        }
852
853
        if(empty($routes))
854
            return FALSE;
855
856
        if(is_null($requestMethod))
857
            $requestMethod = $_SERVER['REQUEST_METHOD'];
858
859
        if(!isset($routes[$requestMethod]))
860
            return FALSE;
861
862
        $routes = $routes[$requestMethod];
863
864
        $founded = FALSE;
0 ignored issues
show
Unused Code introduced by
$founded is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
865
        $matches = array();
0 ignored issues
show
Unused Code introduced by
$matches is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
866
867
        $path = trim($path);
868
869
        if($path == '')
870
        {
871
            return self::$defaultController;
872
        }
873
874
        foreach( [$path, $path.'/index'] as $findPath )
875
        {
876
            foreach($routes as $route)
877
            {
878
                $compiled = $route->compiled;
879
880
                if($findPath == key($compiled))
881
                    return $route;
882
            }
883
        }
884
885
        return FALSE;
886
    }
887
888
    /**
889
     * Returns an array with the valid HTTP Verbs used in routes
890
     *
891
     * @return array
892
     *
893
     * @access public
894
     * @static
895
     */
896
    public static function getHTTPVerbs()
897
    {
898
        return self::$http_verbs;
899
    }
900
901
902
    /**
903
     * Set the 404 error controller ($route['404_override'])
904
     *
905
     * @param  string  $controller
906
     * @param  string  $namespace (Optional)
0 ignored issues
show
Bug introduced by
There is no parameter named $namespace. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
907
     *
908
     * @return void
909
     *
910
     * @access public
911
     * @static
912
     */
913
    public static function set404($controller, $path = '404')
914
    {
915
        self::$_404page = (object)
916
        [
917
            'controller' => $controller,
918
            'path'       => $path
919
        ];
920
    }
921
922
    /**
923
     * Get the 404 route
924
     *
925
     * @return array $_404page
926
     *
927
     * @return object | null
928
     *
929
     * @access public
930
     * @static
931
     */
932
    public static function get404()
933
    {
934
        return self::$_404page;
935
    }
936
937
    /**
938
     * Set the 'translate_uri_dashes' value ($route['translate_uri_dashes'])
939
     *
940
     * @param  $value
941
     *
942
     * @return void
943
     *
944
     * @access public
945
     * @static
946
     */
947
    public static function setTrasnlateUriDashes($value)
948
    {
949
        self::$translateDashes = (bool) $value;
0 ignored issues
show
Documentation Bug introduced by
It seems like (bool) $value of type boolean is incompatible with the declared type object<Luthier\Core\Route> of property $translateDashes.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
950
    }
951
}