Complex classes like Router 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 Router, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
19 | class Router |
||
20 | { |
||
21 | |||
22 | use SingletonTrait; |
||
23 | |||
24 | protected $routing; |
||
25 | protected $slugs; |
||
26 | private $domains; |
||
27 | /** |
||
28 | * @var Finder $finder |
||
29 | */ |
||
30 | private $finder; |
||
31 | /** |
||
32 | * @var \PSFS\base\Cache $cache |
||
33 | */ |
||
34 | private $cache; |
||
35 | /** |
||
36 | * @var \PSFS\base\Security $session |
||
37 | */ |
||
38 | private $session; |
||
39 | /** |
||
40 | * @var bool headersSent |
||
41 | */ |
||
42 | protected $headersSent = false; |
||
43 | |||
44 | /** |
||
45 | * Constructor Router |
||
46 | * @throws ConfigException |
||
47 | */ |
||
48 | 7 | public function __construct() |
|
49 | { |
||
50 | 7 | $this->finder = new Finder(); |
|
51 | 7 | $this->cache = Cache::getInstance(); |
|
52 | 7 | $this->session = Security::getInstance(); |
|
53 | 7 | $this->init(); |
|
54 | 6 | } |
|
55 | |||
56 | /** |
||
57 | * Inicializador Router |
||
58 | * @throws ConfigException |
||
59 | */ |
||
60 | 2 | public function init() |
|
70 | |||
71 | /** |
||
72 | * Método que deriva un error HTTP de página no encontrada |
||
73 | * |
||
74 | * @param \Exception $e |
||
75 | * |
||
76 | * @return string HTML |
||
77 | */ |
||
78 | public function httpNotFound(\Exception $e = NULL) |
||
79 | { |
||
80 | $template = Template::getInstance() |
||
81 | ->setStatus($e->getCode()); |
||
82 | if (preg_match('/json/i', Request::getInstance()->getServer('CONTENT_TYPE'))) { |
||
83 | return $template->output(json_encode(array( |
||
84 | "success" => FALSE, |
||
85 | "error" => $e->getMessage(), |
||
86 | )), 'application/json'); |
||
87 | } else { |
||
88 | if (NULL === $e) { |
||
89 | $e = new \Exception(_('Página no encontrada'), 404); |
||
90 | } |
||
91 | |||
92 | return $template->render('error.html.twig', array( |
||
93 | 'exception' => $e, |
||
94 | 'trace' => $e->getTraceAsString(), |
||
95 | 'error_page' => TRUE, |
||
96 | )); |
||
97 | } |
||
98 | } |
||
99 | |||
100 | /** |
||
101 | * Método que devuelve las rutas |
||
102 | * @return string|null |
||
103 | */ |
||
104 | public function getSlugs() |
||
108 | |||
109 | /** |
||
110 | * Método que calcula el objeto a enrutar |
||
111 | * |
||
112 | * @param string $route |
||
113 | * |
||
114 | * @throws \Exception |
||
115 | * @return string HTML |
||
116 | */ |
||
117 | public function execute($route) |
||
151 | |||
152 | /** |
||
153 | * Check CROS requests |
||
154 | */ |
||
155 | private function checkCORS() |
||
175 | |||
176 | /** |
||
177 | * Método que busca el componente que ejecuta la ruta |
||
178 | * |
||
179 | * @param string $route |
||
180 | * |
||
181 | * @throws \Exception |
||
182 | */ |
||
183 | protected function searchAction($route) |
||
184 | { |
||
185 | //Revisamos si tenemos la ruta registrada |
||
186 | $parts = parse_url($route); |
||
187 | $path = (array_key_exists('path', $parts)) ? $parts['path'] : $route; |
||
188 | $httpRequest = Request::getInstance()->getMethod(); |
||
189 | foreach ($this->routing as $pattern => $action) { |
||
190 | list($httpMethod, $routePattern) = $this->extractHttpRoute($pattern); |
||
191 | $matched = $this->matchRoutePattern($routePattern, $path); |
||
192 | if ($matched && ($httpMethod === "ALL" || $httpRequest === $httpMethod)) { |
||
193 | $get = $this->extractComponents($route, $routePattern); |
||
194 | /** @var $class \PSFS\base\types\Controller */ |
||
195 | $class = $this->getClassToCall($action); |
||
196 | try { |
||
197 | return $this->executeCachedRoute($route, $action, $class, $get); |
||
198 | } catch (\Exception $e) { |
||
199 | Logger::getInstance()->debugLog($e->getMessage(), array($e->getFile(), $e->getLine())); |
||
200 | throw new RouterException($e->getMessage(), 404, $e); |
||
201 | } |
||
202 | } |
||
203 | } |
||
204 | throw new RouterException(_("Ruta no encontrada")); |
||
205 | } |
||
206 | |||
207 | /** |
||
208 | * Método que manda las cabeceras de autenticación |
||
209 | * @return string HTML |
||
210 | */ |
||
211 | protected function sentAuthHeader() |
||
215 | |||
216 | /** |
||
217 | * Método que redirige a la pantalla web del login |
||
218 | * |
||
219 | * @param string $route |
||
220 | * |
||
221 | * @return string HTML |
||
222 | */ |
||
223 | public function redirectLogin($route) |
||
227 | |||
228 | /** |
||
229 | * Método que chequea el acceso a una zona restringida |
||
230 | * |
||
231 | * @param string $route |
||
232 | * |
||
233 | * @throws AccessDeniedException |
||
234 | */ |
||
235 | protected function checkRestrictedAccess($route) |
||
247 | |||
248 | /** |
||
249 | * Método que extrae de la url los parámetros REST |
||
250 | * |
||
251 | * @param string $route |
||
252 | * |
||
253 | * @param string $pattern |
||
254 | * |
||
255 | * @return array |
||
256 | */ |
||
257 | protected function extractComponents($route, $pattern) |
||
273 | |||
274 | /** |
||
275 | * Método que regenera el fichero de rutas |
||
276 | * @throws ConfigException |
||
277 | */ |
||
278 | 2 | public function hydrateRouting() |
|
279 | { |
||
280 | 2 | $base = SOURCE_DIR; |
|
281 | 2 | $modules = realpath(CORE_DIR); |
|
282 | 2 | $this->routing = $this->inspectDir($base, "PSFS", array()); |
|
283 | 1 | if (file_exists($modules)) { |
|
284 | $this->routing = $this->inspectDir($modules, "", $this->routing); |
||
285 | } |
||
286 | 1 | $this->cache->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . "domains.json", $this->domains, Cache::JSON, TRUE); |
|
287 | 1 | $home = Config::getInstance()->get('home_action'); |
|
288 | 1 | if (NULL !== $home || $home !== '') { |
|
289 | 1 | $home_params = NULL; |
|
290 | 1 | foreach ($this->routing as $pattern => $params) { |
|
291 | 1 | list($method, $route) = $this->extractHttpRoute($pattern); |
|
292 | 1 | if (preg_match("/" . preg_quote($route, "/") . "$/i", "/" . $home)) { |
|
293 | $home_params = $params; |
||
294 | } |
||
295 | 1 | } |
|
296 | 1 | if (NULL !== $home_params) { |
|
297 | $this->routing['/'] = $home_params; |
||
298 | } |
||
299 | 1 | } |
|
300 | 1 | } |
|
301 | |||
302 | /** |
||
303 | * Método que inspecciona los directorios en busca de clases que registren rutas |
||
304 | * |
||
305 | * @param string $origen |
||
306 | * @param string $namespace |
||
307 | * @param array $routing |
||
308 | * |
||
309 | * @return array |
||
310 | * @throws ConfigException |
||
311 | */ |
||
312 | 2 | private function inspectDir($origen, $namespace = 'PSFS', $routing) |
|
313 | { |
||
314 | 2 | $files = $this->finder->files()->in($origen)->path('/(controller|api)/i')->name("*.php"); |
|
315 | 2 | foreach ($files as $file) { |
|
316 | 2 | $filename = str_replace("/", '\\', str_replace($origen, '', $file->getPathname())); |
|
317 | 2 | $routing = $this->addRouting($namespace . str_replace('.php', '', $filename), $routing); |
|
318 | 2 | } |
|
319 | 1 | $this->finder = new Finder(); |
|
320 | |||
321 | 1 | return $routing; |
|
322 | } |
||
323 | |||
324 | /** |
||
325 | * Método que añade nuevas rutas al array de referencia |
||
326 | * |
||
327 | * @param string $namespace |
||
328 | * @param array $routing |
||
329 | * |
||
330 | * @return array |
||
331 | * @throws ConfigException |
||
332 | */ |
||
333 | 2 | private function addRouting($namespace, $routing) |
|
334 | { |
||
335 | 2 | if (class_exists($namespace)) { |
|
336 | 2 | $reflection = new \ReflectionClass($namespace); |
|
337 | 2 | if (FALSE === $reflection->isAbstract() && FALSE === $reflection->isInterface()) { |
|
338 | 2 | $this->extractDomain($reflection); |
|
339 | 2 | $classComments = $reflection->getDocComment(); |
|
340 | 2 | preg_match('/@api\ (.*)\n/im', $classComments, $apiPath); |
|
341 | 2 | $api = ''; |
|
342 | 2 | if (count($apiPath)) { |
|
343 | $api = array_key_exists(1, $apiPath) ? $apiPath[1] : $api; |
||
344 | } |
||
345 | 2 | foreach ($reflection->getMethods() as $method) { |
|
346 | 2 | if ($method->isPublic()) { |
|
347 | 2 | $docComments = $method->getDocComment(); |
|
348 | 2 | preg_match('/@route\ (.*)\n/i', $docComments, $sr); |
|
349 | 2 | if (count($sr)) { |
|
350 | 2 | list($regex, $default, $params) = $this->extractReflectionParams($sr, $method); |
|
351 | 2 | if (strlen($api)) { |
|
352 | $regex = str_replace('{__API__}', $api, $regex); |
||
353 | $default = str_replace('{__API__}', $api, $default); |
||
354 | } |
||
355 | 2 | $httpMethod = $this->extractReflectionHttpMethod($docComments); |
|
356 | 2 | $visible = $this->extractReflectionVisibility($docComments); |
|
357 | 2 | $expiration = $this->extractReflectionCacheability($docComments); |
|
358 | 2 | $routing[$httpMethod . "#|#" . $regex] = array( |
|
359 | 2 | "class" => $namespace, |
|
360 | 2 | "method" => $method->getName(), |
|
361 | 2 | "params" => $params, |
|
362 | 2 | "default" => $default, |
|
363 | 2 | "visible" => $visible, |
|
364 | 2 | "http" => $httpMethod, |
|
365 | 2 | "cache" => $expiration, |
|
366 | ); |
||
367 | 2 | } |
|
368 | 2 | } |
|
369 | 2 | } |
|
370 | 2 | } |
|
371 | 2 | } |
|
372 | |||
373 | 2 | return $routing; |
|
374 | } |
||
375 | |||
376 | /** |
||
377 | * Método que extrae de la ReflectionClass los datos necesarios para componer los dominios en los templates |
||
378 | * |
||
379 | * @param \ReflectionClass $class |
||
380 | * |
||
381 | * @return Router |
||
382 | * @throws ConfigException |
||
383 | */ |
||
384 | 2 | protected function extractDomain($class) |
|
385 | { |
||
386 | //Calculamos los dominios para las plantillas |
||
387 | 2 | if ($class->hasConstant("DOMAIN")) { |
|
388 | 2 | $domain = "@" . $class->getConstant("DOMAIN") . "/"; |
|
389 | 2 | $path = dirname($class->getFileName()) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR; |
|
390 | 2 | $path = realpath($path) . DIRECTORY_SEPARATOR; |
|
391 | 2 | $tpl_path = "templates"; |
|
392 | 2 | $public_path = "public"; |
|
393 | 2 | $model_path = "models"; |
|
394 | 2 | if (!preg_match("/ROOT/", $domain)) { |
|
395 | $tpl_path = ucfirst($tpl_path); |
||
396 | $public_path = ucfirst($public_path); |
||
397 | $model_path = ucfirst($model_path); |
||
398 | } |
||
399 | 2 | if ($class->hasConstant("TPL")) { |
|
400 | $tpl_path .= DIRECTORY_SEPARATOR . $class->getConstant("TPL"); |
||
401 | } |
||
402 | 2 | $this->domains[$domain] = array( |
|
403 | 2 | "template" => $path . $tpl_path, |
|
404 | 2 | "model" => $path . $model_path, |
|
405 | 2 | "public" => $path . $public_path, |
|
406 | ); |
||
407 | 2 | } |
|
408 | |||
409 | 2 | return $this; |
|
410 | } |
||
411 | |||
412 | /** |
||
413 | * Método que genera las urls amigables para usar dentro del framework |
||
414 | * @return Router |
||
415 | */ |
||
416 | 1 | public function simpatize() |
|
426 | |||
427 | /** |
||
428 | * Método que devuelve el slug de un string dado |
||
429 | * |
||
430 | * @param string $text |
||
431 | * |
||
432 | * @return string |
||
433 | */ |
||
434 | 1 | private function slugify($text) |
|
459 | |||
460 | /** |
||
461 | * Método que devuelve una ruta del framework |
||
462 | * |
||
463 | * @param string $slug |
||
464 | * @param boolean $absolute |
||
465 | * @param array $params |
||
466 | * |
||
467 | * @return string|null |
||
468 | * @throws RouterException |
||
469 | */ |
||
470 | public function getRoute($slug = '', $absolute = FALSE, $params = NULL) |
||
487 | |||
488 | /** |
||
489 | * Método que devuelve las rutas de administración |
||
490 | * @return array |
||
491 | */ |
||
492 | 1 | public function getAdminRoutes() |
|
524 | |||
525 | /** |
||
526 | * Método que devuelve le controlador del admin |
||
527 | * @return Admin |
||
528 | */ |
||
529 | public function getAdmin() |
||
533 | |||
534 | /** |
||
535 | * Método que extrae los dominios |
||
536 | * @return array|null |
||
537 | */ |
||
538 | public function getDomains() |
||
539 | { |
||
540 | return $this->domains; |
||
541 | } |
||
542 | |||
543 | /** |
||
544 | * Método que extrae el controller a invocar |
||
545 | * |
||
546 | * @param string $action |
||
547 | * |
||
548 | * @return Object |
||
549 | */ |
||
550 | protected function getClassToCall($action) |
||
559 | |||
560 | /** |
||
561 | * Método que compara la ruta web con la guardada en la cache |
||
562 | * |
||
563 | * @param $routePattern |
||
564 | * @param $path |
||
565 | * |
||
566 | * @return bool |
||
567 | */ |
||
568 | protected function matchRoutePattern($routePattern, $path) |
||
578 | |||
579 | /** |
||
580 | * @param $pattern |
||
581 | * |
||
582 | * @return array |
||
583 | */ |
||
584 | 1 | protected function extractHttpRoute($pattern) |
|
594 | |||
595 | /** |
||
596 | * Método que extrae los parámetros de una función |
||
597 | * |
||
598 | * @param array $sr |
||
599 | * @param \ReflectionMethod $method |
||
600 | * |
||
601 | * @return array |
||
602 | */ |
||
603 | 2 | private function extractReflectionParams($sr, $method) |
|
618 | |||
619 | /** |
||
620 | * Método que extrae el método http |
||
621 | * |
||
622 | * @param string $docComments |
||
623 | * |
||
624 | * @return string |
||
625 | */ |
||
626 | 2 | private function extractReflectionHttpMethod($docComments) |
|
632 | |||
633 | /** |
||
634 | * Método que extrae la visibilidad de una ruta |
||
635 | * |
||
636 | * @param string $docComments |
||
637 | * |
||
638 | * @return bool |
||
639 | */ |
||
640 | 2 | private function extractReflectionVisibility($docComments) |
|
646 | |||
647 | /** |
||
648 | * Método que extrae el parámetro de caché |
||
649 | * |
||
650 | * @param string $docComments |
||
651 | * |
||
652 | * @return bool |
||
653 | */ |
||
654 | 2 | private function extractReflectionCacheability($docComments) |
|
660 | |||
661 | /** |
||
662 | * Método que ejecuta una acción del framework y revisa si lo tenemos cacheado ya o no |
||
663 | * |
||
664 | * @param string $route |
||
665 | * @param array $action |
||
666 | * @param types\Controller $class |
||
667 | * @param array $params |
||
668 | */ |
||
669 | protected function executeCachedRoute($route, $action, $class, $params = NULL) |
||
690 | |||
691 | /** |
||
692 | * Parse slugs to create translations |
||
693 | * |
||
694 | * @param string $absoluteTranslationFileName |
||
695 | */ |
||
696 | 1 | private function generateSlugs($absoluteTranslationFileName) |
|
716 | |||
717 | /** |
||
718 | * Create translation file if not exists |
||
719 | * |
||
720 | * @param string $absoluteTranslationFileName |
||
721 | * |
||
722 | * @return array |
||
723 | */ |
||
724 | 1 | private function generateTranslationsFile($absoluteTranslationFileName) |
|
735 | } |
||
736 |
Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.