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 | public function __construct()  | 
            ||
| 49 |         { | 
            ||
| 50 | $this->finder = new Finder();  | 
            ||
| 51 | $this->cache = Cache::getInstance();  | 
            ||
| 52 | $this->session = Security::getInstance();  | 
            ||
| 53 | $this->init();  | 
            ||
| 54 | }  | 
            ||
| 55 | |||
| 56 | /**  | 
            ||
| 57 | * Inicializador Router  | 
            ||
| 58 | * @throws ConfigException  | 
            ||
| 59 | */  | 
            ||
| 60 | public function init()  | 
            ||
| 61 |         { | 
            ||
| 62 |             if (!file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . "urls.json") || Config::getInstance()->getDebugMode()) { | 
            ||
| 63 | $this->hydrateRouting();  | 
            ||
| 64 | $this->simpatize();  | 
            ||
| 65 |             } else { | 
            ||
| 66 | list($this->routing, $this->slugs) = $this->cache->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . "urls.json", Cache::JSON, TRUE);  | 
            ||
| 67 | $this->domains = $this->cache->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . "domains.json", Cache::JSON, TRUE);  | 
            ||
| 68 | }  | 
            ||
| 69 | }  | 
            ||
| 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)  | 
            ||
| 118 |         { | 
            ||
| 119 |             try { | 
            ||
| 120 | //Check CORS for requests  | 
            ||
| 121 | $this->checkCORS();  | 
            ||
| 122 | // Checks restricted access  | 
            ||
| 123 | $this->checkRestrictedAccess($route);  | 
            ||
| 124 | |||
| 125 | //Search action and execute  | 
            ||
| 126 | return $this->searchAction($route);  | 
            ||
| 127 |             } catch (AccessDeniedException $e) { | 
            ||
| 128 |                 Logger::getInstance()->debugLog(_('Solicitamos credenciales de acceso a zona restringida')); | 
            ||
| 129 |                 if ('login' === Config::getInstance()->get('admin_login')) { | 
            ||
| 130 | return $this->redirectLogin($route);  | 
            ||
| 131 |                 } else { | 
            ||
| 132 | return $this->sentAuthHeader();  | 
            ||
| 133 | }  | 
            ||
| 134 |             } catch (RouterException $r) { | 
            ||
| 135 |                 if (FALSE !== preg_match('/\/$/', $route)) { | 
            ||
| 136 |                     if (preg_match('/admin/', $route)) { | 
            ||
| 137 |                         $default = Config::getInstance()->get('admin_action'); | 
            ||
| 138 |                     } else { | 
            ||
| 139 |                         $default = Config::getInstance()->get('home_action'); | 
            ||
| 140 | }  | 
            ||
| 141 | |||
| 142 | return $this->execute($this->getRoute($default));  | 
            ||
| 143 | }  | 
            ||
| 144 |             } catch (\Exception $e) { | 
            ||
| 145 | Logger::getInstance()->errorLog($e->getMessage());  | 
            ||
| 146 | throw $e;  | 
            ||
| 147 | }  | 
            ||
| 148 | |||
| 149 | return $this->httpNotFound();  | 
            ||
| 150 | }  | 
            ||
| 151 | |||
| 152 | /**  | 
            ||
| 153 | * Check CROS requests  | 
            ||
| 154 | */  | 
            ||
| 155 | private function checkCORS()  | 
            ||
| 156 |         { | 
            ||
| 157 |             $corsEnabled = Config::getInstance()->get('cors.enabled'); | 
            ||
| 158 | $request = Request::getInstance();  | 
            ||
| 159 |             if (NULL !== $corsEnabled && null !== $request->getServer('HTTP_REFERER')) { | 
            ||
| 160 |                 if($corsEnabled == '*' || preg_match($corsEnabled, $request->getServer('HTTP_REFERER'))) { | 
            ||
| 161 |                     if (!$this->headersSent) { | 
            ||
| 162 |                         header("Access-Control-Allow-Credentials: true"); | 
            ||
| 163 |                         header("Access-Control-Allow-Origin: *"); | 
            ||
| 164 |                         header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); | 
            ||
| 165 |                         header("Access-Control-Allow-Headers: Access-Control-Allow-Methods, Access-Control-Allow-Headers, Access-Control-Allow-Origin, Origin, X-Requested-With, Content-Type, Accept, Authorization"); | 
            ||
| 166 | $this->headersSent = true;  | 
            ||
| 167 | }  | 
            ||
| 168 |                     if(Request::getInstance()->getMethod() == 'OPTIONS') { | 
            ||
| 169 | header( "HTTP/1.1 200 OK" );  | 
            ||
| 170 | exit();  | 
            ||
| 171 | }  | 
            ||
| 172 | }  | 
            ||
| 173 | }  | 
            ||
| 174 | }  | 
            ||
| 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 | private function hydrateRouting()  | 
            ||
| 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 | private function inspectDir($origen, $namespace = 'PSFS', $routing)  | 
            ||
| 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 | private function addRouting($namespace, $routing)  | 
            ||
| 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 | protected function extractDomain($class)  | 
            ||
| 411 | |||
| 412 | /**  | 
            ||
| 413 | * Método que genera las urls amigables para usar dentro del framework  | 
            ||
| 414 | * @return Router  | 
            ||
| 415 | */  | 
            ||
| 416 | private 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 | 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 | 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()  | 
            ||
| 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 | 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 | 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 | 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 | 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 | 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 | private function generateSlugs($absoluteTranslationFileName)  | 
            ||
| 716 | |||
| 717 | /**  | 
            ||
| 718 | * Create translation file if not exists  | 
            ||
| 719 | *  | 
            ||
| 720 | * @param string $absoluteTranslationFileName  | 
            ||
| 721 | *  | 
            ||
| 722 | * @return array  | 
            ||
| 723 | */  | 
            ||
| 724 | private function generateTranslationsFile($absoluteTranslationFileName)  | 
            ||
| 735 | }  | 
            ||
| 736 |