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 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 |
||
13 | class Route { |
||
|
|||
14 | use Module, Events; |
||
15 | |||
16 | public static $routes, |
||
17 | $base = '', |
||
18 | $prefix = [], |
||
19 | $group = [], |
||
20 | $optimized_tree = []; |
||
21 | |||
22 | protected $URLPattern = '', |
||
23 | $pattern = '', |
||
24 | $dynamic = false, |
||
25 | $callback = null, |
||
26 | $methods = [], |
||
27 | $befores = [], |
||
28 | $afters = [], |
||
29 | |||
30 | $rules = [], |
||
31 | $response = ''; |
||
32 | |||
33 | |||
34 | /** |
||
35 | * Create a new route definition. This method permits a fluid interface. |
||
36 | * |
||
37 | * @param string $URLPattern The URL pattern, can be used named parameters for variables extraction |
||
38 | * @param $callback The callback to invoke on route match. |
||
39 | * @param string $method The HTTP method for which the route must respond. |
||
40 | * @return Route |
||
41 | */ |
||
42 | public function __construct($URLPattern, $callback = null, $method='get'){ |
||
43 | $prefix = static::$prefix ? rtrim(implode('',static::$prefix),'/') : ''; |
||
44 | $pattern = "/" . trim($URLPattern, "/"); |
||
45 | // Adjust / optionality with dynamic patterns |
||
46 | // Ex: /test/(:a) ===> /test(/:a) |
||
47 | $this->URLPattern = str_replace('//','/',str_replace('/(','(/', rtrim("{$prefix}{$pattern}","/"))); |
||
48 | |||
49 | $this->dynamic = $this->isDynamic($this->URLPattern); |
||
50 | $this->pattern = $this->dynamic ? $this->compilePatternAsRegex($this->URLPattern, $this->rules) : $this->URLPattern; |
||
51 | $this->callback = $callback; |
||
52 | |||
53 | // We will use hash-checks, for O(1) complexity vs O(n) |
||
54 | $this->methods[$method] = 1; |
||
55 | return static::add($this); |
||
56 | } |
||
57 | |||
58 | /** |
||
59 | * Check if route match on a specified URL and HTTP Method. |
||
60 | * @param [type] $URL The URL to check against. |
||
61 | * @param string $method The HTTP Method to check against. |
||
62 | * @return boolean |
||
63 | */ |
||
64 | public function match($URL,$method='get'){ |
||
65 | $method = strtolower($method); |
||
66 | |||
67 | // * is an http method wildcard |
||
68 | if (empty($this->methods[$method]) && empty($this->methods['*'])) return false; |
||
69 | $URL = rtrim($URL,'/'); |
||
70 | $args = []; |
||
71 | if ( $this->dynamic |
||
72 | ? preg_match($this->pattern,$URL,$args) |
||
73 | : $URL == rtrim($this->pattern,'/') |
||
74 | ){ |
||
75 | foreach ( $args as $key => $value ) { |
||
76 | if ( false === is_string($key) ) unset($args[$key]); |
||
77 | } |
||
78 | return $args; |
||
79 | } |
||
80 | return false; |
||
81 | } |
||
82 | |||
83 | /** |
||
84 | * Clears all stored routes definitions to pristine conditions. |
||
85 | * @return void |
||
86 | */ |
||
87 | public static function reset(){ |
||
88 | static::$routes = []; |
||
89 | static::$base = ''; |
||
90 | static::$prefix = []; |
||
91 | static::$group = []; |
||
92 | static::$optimized_tree = []; |
||
93 | } |
||
94 | |||
95 | /** |
||
96 | * Run one of the mapped callbacks to a passed HTTP Method. |
||
97 | * @param array $args The arguments to be passed to the callback |
||
98 | * @param string $method The HTTP Method requested. |
||
99 | * @return array The callback response. |
||
100 | */ |
||
101 | public function run(array $args, $method='get'){ |
||
102 | $method = strtolower($method); |
||
103 | $append_echoed_text = Options::get('core.route.append_echoed_text',true); |
||
104 | |||
105 | // Call direct befores |
||
106 | View Code Duplication | if ( $this->befores ) { |
|
107 | // Reverse befores order |
||
108 | foreach (array_reverse($this->befores) as $mw) { |
||
109 | static::trigger('before', $this, $mw); |
||
110 | Event::trigger('core.route.before', $this, $mw); |
||
111 | ob_start(); |
||
112 | $mw_result = call_user_func($mw); |
||
113 | $raw_echoed = ob_get_clean(); |
||
114 | if ($append_echoed_text) Response::add($raw_echoed); |
||
115 | if ( false === $mw_result ) { |
||
116 | return ['']; |
||
117 | } else { |
||
118 | Response::add($mw_result); |
||
119 | } |
||
120 | } |
||
121 | } |
||
122 | |||
123 | $callback = (is_array($this->callback) && isset($this->callback[$method])) |
||
124 | ? $this->callback[$method] |
||
125 | : $this->callback; |
||
126 | |||
127 | if (is_callable($callback)) { |
||
128 | Response::type( Options::get('core.route.response_default_type', Response::TYPE_HTML) ); |
||
129 | |||
130 | ob_start(); |
||
131 | $view_results = call_user_func_array($callback, $args); |
||
132 | $raw_echoed = ob_get_clean(); |
||
133 | |||
134 | if ($append_echoed_text) Response::add($raw_echoed); |
||
135 | Response::add($view_results); |
||
136 | } |
||
137 | |||
138 | // Apply afters |
||
139 | View Code Duplication | if ( $this->afters ) { |
|
140 | foreach ($this->afters as $mw) { |
||
141 | static::trigger('after', $this, $mw); |
||
142 | Event::trigger('core.route.after', $this, $mw); |
||
143 | ob_start(); |
||
144 | $mw_result = call_user_func($mw); |
||
145 | $raw_echoed = ob_get_clean(); |
||
146 | if ($append_echoed_text) Response::add($raw_echoed); |
||
147 | if ( false === $mw_result ) { |
||
148 | return ['']; |
||
149 | } else { |
||
150 | Response::add($mw_result); |
||
151 | } |
||
152 | } |
||
153 | } |
||
154 | |||
155 | static::trigger('end', $this); |
||
156 | Event::trigger('core.route.end', $this); |
||
157 | |||
158 | return [Filter::with('core.route.response', Response::body())]; |
||
159 | } |
||
160 | |||
161 | /** |
||
162 | * Check if route match URL and HTTP Method and run if it is valid. |
||
163 | * @param [type] $URL The URL to check against. |
||
164 | * @param string $method The HTTP Method to check against. |
||
165 | * @return array The callback response. |
||
166 | */ |
||
167 | public function runIfMatch($URL, $method='get'){ |
||
170 | |||
171 | /** |
||
172 | * Start a route definition, default to HTTP GET. |
||
173 | * @param string $URLPattern The URL to match against, you can define named segments to be extracted and passed to the callback. |
||
174 | * @param $callback The callback to be invoked (with variables extracted from the route if present) when the route match the request URI. |
||
175 | * @return Route |
||
176 | */ |
||
177 | public static function on($URLPattern, $callback = null){ |
||
180 | |||
181 | /** |
||
182 | * Start a route definition with HTTP Method via GET. |
||
183 | * @param string $URLPattern The URL to match against, you can define named segments to be extracted and passed to the callback. |
||
184 | * @param $callback The callback to be invoked (with variables extracted from the route if present) when the route match the request URI. |
||
185 | * @return Route |
||
186 | */ |
||
187 | public static function get($URLPattern, $callback = null){ |
||
190 | |||
191 | /** |
||
192 | * Start a route definition with HTTP Method via POST. |
||
193 | * @param string $URLPattern The URL to match against, you can define named segments to be extracted and passed to the callback. |
||
194 | * @param $callback The callback to be invoked (with variables extracted from the route if present) when the route match the request URI. |
||
195 | * @return Route |
||
196 | */ |
||
197 | public static function post($URLPattern, $callback = null){ |
||
200 | |||
201 | /** |
||
202 | * Start a route definition, for any HTTP Method (using * wildcard). |
||
203 | * @param string $URLPattern The URL to match against, you can define named segments to be extracted and passed to the callback. |
||
204 | * @param $callback The callback to be invoked (with variables extracted from the route if present) when the route match the request URI. |
||
205 | * @return Route |
||
206 | */ |
||
207 | public static function any($URLPattern, $callback = null){ |
||
210 | |||
211 | /** |
||
212 | * Bind a callback to the route definition |
||
213 | * @param $callback The callback to be invoked (with variables extracted from the route if present) when the route match the request URI. |
||
214 | * @return Route |
||
215 | */ |
||
216 | public function & with($callback){ |
||
220 | |||
221 | /** |
||
222 | * Bind a middleware callback to invoked before the route definition |
||
223 | * @param callable $before The callback to be invoked ($this is binded to the route object). |
||
224 | * @return Route |
||
225 | */ |
||
226 | public function & before($callback){ |
||
230 | |||
231 | /** |
||
232 | * Bind a middleware callback to invoked after the route definition |
||
233 | * @param $callback The callback to be invoked ($this is binded to the route object). |
||
234 | * @return Route |
||
235 | */ |
||
236 | public function & after($callback){ |
||
240 | |||
241 | /** |
||
242 | * Defines the HTTP Methods to bind the route onto. |
||
243 | * |
||
244 | * Example: |
||
245 | * <code> |
||
246 | * Route::on('/test')->via('get','post','delete'); |
||
247 | * </code> |
||
248 | * |
||
249 | * @return Route |
||
250 | */ |
||
251 | public function & via(...$methods){ |
||
258 | |||
259 | /** |
||
260 | * Defines the regex rules for the named parameter in the current URL pattern |
||
261 | * |
||
262 | * Example: |
||
263 | * <code> |
||
264 | * Route::on('/proxy/:number/:url') |
||
265 | * ->rules([ |
||
266 | * 'number' => '\d+', |
||
267 | * 'url' => '.+', |
||
268 | * ]); |
||
269 | * </code> |
||
270 | * |
||
271 | * @param array $rules The regex rules |
||
272 | * @return Route |
||
273 | */ |
||
274 | public function & rules(array $rules){ |
||
281 | |||
282 | /** |
||
283 | * Map a HTTP Method => callable array to a route. |
||
284 | * |
||
285 | * Example: |
||
286 | * <code> |
||
287 | * Route::map('/test'[ |
||
288 | * 'get' => function(){ echo "HTTP GET"; }, |
||
289 | * 'post' => function(){ echo "HTTP POST"; }, |
||
290 | * 'put' => function(){ echo "HTTP PUT"; }, |
||
291 | * 'delete' => function(){ echo "HTTP DELETE"; }, |
||
292 | * ]); |
||
293 | * </code> |
||
294 | * |
||
295 | * @param string $URLPattern The URL to match against, you can define named segments to be extracted and passed to the callback. |
||
296 | * @param array $callbacks The HTTP Method => callable map. |
||
297 | * @return Route |
||
298 | */ |
||
299 | public static function & map($URLPattern, $callbacks = []){ |
||
310 | |||
311 | /** |
||
312 | * Compile an URL schema to a PREG regular expression. |
||
313 | * @param string $pattern The URL schema. |
||
314 | * @return string The compiled PREG RegEx. |
||
315 | */ |
||
316 | protected static function compilePatternAsRegex($pattern, $rules=[]){ |
||
321 | |||
322 | /** |
||
323 | * Extract the URL schema variables from the passed URL. |
||
324 | * @param string $pattern The URL schema with the named parameters |
||
325 | * @param string $URL The URL to process, if omitted the current request URI will be used. |
||
326 | * @param boolean $cut If true don't limit the matching to the whole URL (used for group pattern extraction) |
||
327 | * @return array The extracted variables |
||
328 | */ |
||
329 | protected static function extractVariablesFromURL($pattern, $URL=null, $cut=false){ |
||
338 | |||
339 | /** |
||
340 | * Check if an URL schema need dynamic matching (regex). |
||
341 | * @param string $pattern The URL schema. |
||
342 | * @return boolean |
||
343 | */ |
||
344 | protected static function isDynamic($pattern){ |
||
347 | |||
348 | /** |
||
349 | * Add a route to the internal route repository. |
||
350 | * @param Route $route |
||
351 | * @return Route |
||
352 | */ |
||
353 | public static function add($route){ |
||
366 | |||
367 | /** |
||
368 | * Define a route group, if not immediately matched internal code will not be invoked. |
||
369 | * @param string $prefix The url prefix for the internal route definitions. |
||
370 | * @param string $callback This callback is invoked on $prefix match of the current request URI. |
||
371 | */ |
||
372 | public static function group($prefix, $callback){ |
||
411 | |||
412 | public static function exitWithError($code, $message="Application Error"){ |
||
417 | |||
418 | public static function optimize(){ |
||
431 | |||
432 | /** |
||
433 | * Start the route dispatcher and resolve the URL request. |
||
434 | * @param string $URL The URL to match onto. |
||
435 | * @return boolean true if a route callback was executed. |
||
436 | */ |
||
437 | public static function dispatch($URL=null, $method=null){ |
||
478 | } |
||
479 | |||
518 |
You can fix this by adding a namespace to your class:
When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.