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 |
||
24 | class Router |
||
25 | { |
||
26 | use SingletonTrait; |
||
27 | |||
28 | protected $routing; |
||
29 | protected $slugs; |
||
30 | private $domains; |
||
31 | /** |
||
32 | * @var Finder $finder |
||
33 | */ |
||
34 | private $finder; |
||
35 | /** |
||
36 | * @var \PSFS\base\Cache $cache |
||
37 | */ |
||
38 | private $cache; |
||
39 | /** |
||
40 | * @var bool headersSent |
||
41 | */ |
||
42 | protected $headersSent = false; |
||
43 | /** |
||
44 | * @var int |
||
45 | */ |
||
46 | protected $cacheType = Cache::JSON; |
||
47 | |||
48 | /** |
||
49 | * Constructor Router |
||
50 | * @throws ConfigException |
||
51 | */ |
||
52 | 1 | public function __construct() |
|
53 | { |
||
54 | 1 | $this->finder = new Finder(); |
|
55 | 1 | $this->cache = Cache::getInstance(); |
|
56 | 1 | $this->init(); |
|
57 | 1 | } |
|
58 | |||
59 | /** |
||
60 | * Inicializador Router |
||
61 | * @throws ConfigException |
||
62 | */ |
||
63 | 1 | public function init() |
|
64 | { |
||
65 | 1 | list($this->routing, $this->slugs) = $this->cache->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . "urls.json", $this->cacheType, TRUE); |
|
|
|||
66 | 1 | $this->domains = $this->cache->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . "domains.json", $this->cacheType, TRUE); |
|
67 | 1 | if (empty($this->routing) || Config::getInstance()->getDebugMode()) { |
|
68 | 1 | $this->debugLoad(); |
|
69 | 1 | } |
|
70 | 1 | $this->checkExternalModules(false); |
|
71 | 1 | } |
|
72 | |||
73 | /** |
||
74 | * Load routes and domains and store them |
||
75 | */ |
||
76 | 1 | private function debugLoad() { |
|
77 | 1 | Logger::log('Begin routes load', LOG_DEBUG); |
|
78 | 1 | $this->hydrateRouting(); |
|
79 | 1 | $this->simpatize(); |
|
80 | 1 | Logger::log('End routes load', LOG_DEBUG); |
|
81 | 1 | } |
|
82 | |||
83 | /** |
||
84 | * Método que deriva un error HTTP de página no encontrada |
||
85 | * |
||
86 | * @param \Exception $e |
||
87 | * @param boolean $isJson |
||
88 | * |
||
89 | * @return string HTML |
||
90 | */ |
||
91 | 1 | public function httpNotFound(\Exception $e = NULL, $isJson = false) |
|
92 | { |
||
93 | Logger::log('Throw not found exception'); |
||
94 | if (NULL === $e) { |
||
95 | Logger::log('Not found page throwed without previous exception', LOG_WARNING); |
||
96 | $e = new \Exception(_('Page not found'), 404); |
||
97 | } |
||
98 | $template = Template::getInstance()->setStatus($e->getCode()); |
||
99 | if (preg_match('/json/i', Request::getInstance()->getServer('CONTENT_TYPE')) || $isJson) { |
||
100 | return $template->output(json_encode(array( |
||
101 | 1 | "success" => FALSE, |
|
102 | "error" => $e->getMessage(), |
||
103 | )), 'application/json'); |
||
104 | } else { |
||
105 | return $template->render('error.html.twig', array( |
||
106 | 'exception' => $e, |
||
107 | 'trace' => $e->getTraceAsString(), |
||
108 | 'error_page' => TRUE, |
||
109 | )); |
||
110 | } |
||
111 | } |
||
112 | |||
113 | /** |
||
114 | * Método que devuelve las rutas |
||
115 | * @return string|null |
||
116 | */ |
||
117 | 1 | public function getSlugs() |
|
118 | { |
||
119 | 1 | return $this->slugs; |
|
120 | } |
||
121 | |||
122 | /** |
||
123 | * @return mixed |
||
124 | */ |
||
125 | 2 | public function getRoutes() { |
|
126 | 2 | return $this->routing; |
|
127 | } |
||
128 | |||
129 | /** |
||
130 | * Method that extract all routes in the platform |
||
131 | * @return array |
||
132 | */ |
||
133 | 1 | public function getAllRoutes() |
|
134 | { |
||
135 | 1 | $routes = []; |
|
136 | 1 | foreach ($this->getRoutes() as $path => $route) { |
|
137 | 1 | if (array_key_exists('slug', $route)) { |
|
138 | 1 | $routes[$route['slug']] = $path; |
|
139 | 1 | } |
|
140 | 1 | } |
|
141 | 1 | return $routes; |
|
142 | } |
||
143 | |||
144 | /** |
||
145 | * Método que calcula el objeto a enrutar |
||
146 | * |
||
147 | * @param string|null $route |
||
148 | * |
||
149 | * @throws \Exception |
||
150 | * @return string HTML |
||
151 | */ |
||
152 | 1 | public function execute($route) |
|
153 | { |
||
154 | 1 | Logger::log('Executing the request'); |
|
155 | try { |
||
156 | //Check CORS for requests |
||
157 | 1 | RequestHelper::checkCORS(); |
|
158 | // Checks restricted access |
||
159 | 1 | SecurityHelper::checkRestrictedAccess($route); |
|
160 | //Search action and execute |
||
161 | 1 | $this->searchAction($route); |
|
162 | 1 | } catch (AccessDeniedException $e) { |
|
163 | Logger::log(_('Solicitamos credenciales de acceso a zona restringida')); |
||
164 | return Admin::staticAdminLogon($route); |
||
165 | 1 | } catch (RouterException $r) { |
|
166 | 1 | Logger::log($r->getMessage(), LOG_WARNING); |
|
167 | 1 | } catch (\Exception $e) { |
|
168 | Logger::log($e->getMessage(), LOG_ERR); |
||
169 | throw $e; |
||
170 | } |
||
171 | |||
172 | 1 | throw new RouterException(_("Página no encontrada"), 404); |
|
173 | } |
||
174 | |||
175 | /** |
||
176 | * Método que busca el componente que ejecuta la ruta |
||
177 | * |
||
178 | * @param string $route |
||
179 | * |
||
180 | * @throws \PSFS\base\exception\RouterException |
||
181 | */ |
||
182 | 1 | protected function searchAction($route) |
|
183 | { |
||
184 | 1 | Logger::log('Searching action to execute: ' . $route, LOG_INFO); |
|
185 | //Revisamos si tenemos la ruta registrada |
||
186 | 1 | $parts = parse_url($route); |
|
187 | 1 | $path = (array_key_exists('path', $parts)) ? $parts['path'] : $route; |
|
188 | 1 | $httpRequest = Request::getInstance()->getMethod(); |
|
189 | 1 | foreach ($this->routing as $pattern => $action) { |
|
190 | 1 | list($httpMethod, $routePattern) = RouterHelper::extractHttpRoute($pattern); |
|
191 | 1 | $matched = RouterHelper::matchRoutePattern($routePattern, $path); |
|
192 | 1 | if ($matched && ($httpMethod === "ALL" || $httpRequest === $httpMethod) && RouterHelper::compareSlashes($routePattern, $path)) { |
|
193 | $get = RouterHelper::extractComponents($route, $routePattern); |
||
194 | /** @var $class \PSFS\base\types\Controller */ |
||
195 | $class = RouterHelper::getClassToCall($action); |
||
196 | try { |
||
197 | $this->executeCachedRoute($route, $action, $class, $get); |
||
198 | } catch (\Exception $e) { |
||
199 | Logger::log($e->getMessage(), LOG_ERR); |
||
200 | throw new \RuntimeException($e->getMessage(), 404, $e); |
||
201 | } |
||
202 | } |
||
203 | 1 | } |
|
204 | 1 | 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() |
||
212 | { |
||
213 | return AdminServices::getInstance()->setAdminHeaders(); |
||
214 | } |
||
215 | |||
216 | /** |
||
217 | * Method that check if the proyect has sub project to include |
||
218 | * @param boolean $hydrateRoute |
||
219 | */ |
||
220 | 1 | private function checkExternalModules($hydrateRoute = true) |
|
221 | { |
||
222 | 1 | $externalModules = Config::getParam('modules.extend'); |
|
223 | 1 | if (null !== $externalModules) { |
|
224 | $externalModules = explode(',', $externalModules); |
||
225 | foreach ($externalModules as &$module) { |
||
226 | $module = preg_replace('/(\\\|\/)/', DIRECTORY_SEPARATOR, $module); |
||
227 | $externalModulePath = VENDOR_DIR . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . 'src'; |
||
228 | if (file_exists($externalModulePath)) { |
||
229 | $externalModule = $this->finder->directories()->in($externalModulePath)->depth(0); |
||
230 | if (!empty($externalModule)) { |
||
231 | foreach ($externalModule as $modulePath) { |
||
232 | $extModule = $modulePath->getBasename(); |
||
233 | $moduleAutoloader = realpath($externalModulePath . DIRECTORY_SEPARATOR . $extModule . DIRECTORY_SEPARATOR . 'autoload.php'); |
||
234 | if (file_exists($moduleAutoloader)) { |
||
235 | @include $moduleAutoloader; |
||
236 | if ($hydrateRoute) { |
||
237 | $this->routing = $this->inspectDir($externalModulePath . DIRECTORY_SEPARATOR . $extModule, '\\' . $extModule, $this->routing); |
||
238 | } |
||
239 | } |
||
240 | } |
||
241 | } |
||
242 | } |
||
243 | } |
||
244 | } |
||
245 | 1 | } |
|
246 | |||
247 | /** |
||
248 | * Method that gather all the routes in the project |
||
249 | */ |
||
250 | 1 | private function generateRouting() |
|
251 | { |
||
252 | 1 | $base = SOURCE_DIR; |
|
253 | 1 | $modulesPath = realpath(CORE_DIR); |
|
254 | 1 | $this->routing = $this->inspectDir($base, "PSFS", array()); |
|
255 | 1 | $this->checkExternalModules(); |
|
256 | 1 | if (file_exists($modulesPath)) { |
|
257 | $modules = $this->finder->directories()->in($modulesPath)->depth(0); |
||
258 | foreach ($modules as $modulePath) { |
||
259 | $module = $modulePath->getBasename(); |
||
260 | $this->routing = $this->inspectDir($modulesPath . DIRECTORY_SEPARATOR . $module, $module, $this->routing); |
||
261 | } |
||
262 | } |
||
263 | 1 | $this->cache->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . "domains.json", $this->domains, Cache::JSON, TRUE); |
|
264 | 1 | } |
|
265 | |||
266 | /** |
||
267 | * Método que regenera el fichero de rutas |
||
268 | * @throws ConfigException |
||
269 | */ |
||
270 | 1 | public function hydrateRouting() |
|
271 | { |
||
272 | 1 | $this->generateRouting(); |
|
273 | 1 | $home = Config::getInstance()->get('home_action'); |
|
274 | 1 | if (NULL !== $home || $home !== '') { |
|
275 | 1 | $home_params = NULL; |
|
276 | 1 | foreach ($this->routing as $pattern => $params) { |
|
277 | 1 | list($method, $route) = RouterHelper::extractHttpRoute($pattern); |
|
278 | 1 | if (preg_match("/" . preg_quote($route, "/") . "$/i", "/" . $home)) { |
|
279 | $home_params = $params; |
||
280 | } |
||
281 | 1 | } |
|
282 | 1 | if (NULL !== $home_params) { |
|
283 | $this->routing['/'] = $home_params; |
||
284 | } |
||
285 | 1 | } |
|
286 | 1 | } |
|
287 | |||
288 | /** |
||
289 | * Método que inspecciona los directorios en busca de clases que registren rutas |
||
290 | * |
||
291 | * @param string $origen |
||
292 | * @param string $namespace |
||
293 | * @param array $routing |
||
294 | * |
||
295 | * @return array |
||
296 | * @throws ConfigException |
||
297 | */ |
||
298 | 1 | private function inspectDir($origen, $namespace = 'PSFS', $routing = []) |
|
299 | { |
||
300 | 1 | $files = $this->finder->files()->in($origen)->path('/(controller|api)/i')->depth(1)->name("*.php"); |
|
301 | 1 | foreach ($files as $file) { |
|
302 | 1 | $filename = str_replace("/", '\\', str_replace($origen, '', $file->getPathname())); |
|
303 | 1 | $routing = $this->addRouting($namespace . str_replace('.php', '', $filename), $routing, $namespace); |
|
304 | 1 | } |
|
305 | 1 | $this->finder = new Finder(); |
|
306 | |||
307 | 1 | return $routing; |
|
308 | } |
||
309 | |||
310 | /** |
||
311 | * Checks that a namespace exists |
||
312 | * @param string $namespace |
||
313 | * @return bool |
||
314 | */ |
||
315 | 1 | public static function exists($namespace) |
|
316 | { |
||
317 | 1 | return (class_exists($namespace) || interface_exists($namespace) || trait_exists($namespace)); |
|
318 | } |
||
319 | |||
320 | /** |
||
321 | * Método que añade nuevas rutas al array de referencia |
||
322 | * |
||
323 | * @param string $namespace |
||
324 | * @param array $routing |
||
325 | * @param string $module |
||
326 | * |
||
327 | * @return array |
||
328 | * @throws ConfigException |
||
329 | */ |
||
330 | 1 | private function addRouting($namespace, &$routing, $module = 'PSFS') |
|
331 | { |
||
332 | 1 | if (self::exists($namespace)) { |
|
333 | 1 | $reflection = new \ReflectionClass($namespace); |
|
334 | 1 | if (FALSE === $reflection->isAbstract() && FALSE === $reflection->isInterface()) { |
|
335 | 1 | $this->extractDomain($reflection); |
|
336 | 1 | $classComments = $reflection->getDocComment(); |
|
337 | 1 | preg_match('/@api\ (.*)\n/im', $classComments, $apiPath); |
|
338 | 1 | $api = ''; |
|
339 | 1 | if (count($apiPath)) { |
|
340 | $api = array_key_exists(1, $apiPath) ? $apiPath[1] : $api; |
||
341 | } |
||
342 | 1 | foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { |
|
343 | 1 | if (preg_match('/@route\ /i', $method->getDocComment())) { |
|
344 | 1 | list($route, $info) = RouterHelper::extractRouteInfo($method, str_replace('\\', '', $api), str_replace('\\', '', $module)); |
|
345 | |||
346 | 1 | if (null !== $route && null !== $info) { |
|
347 | 1 | $info['class'] = $namespace; |
|
348 | 1 | $routing[$route] = $info; |
|
349 | 1 | } |
|
350 | 1 | } |
|
351 | 1 | } |
|
352 | 1 | } |
|
353 | 1 | } |
|
354 | |||
355 | 1 | return $routing; |
|
356 | } |
||
357 | |||
358 | /** |
||
359 | * Método que extrae de la ReflectionClass los datos necesarios para componer los dominios en los templates |
||
360 | * |
||
361 | * @param \ReflectionClass $class |
||
362 | * |
||
363 | * @return Router |
||
364 | * @throws ConfigException |
||
365 | */ |
||
366 | 1 | protected function extractDomain(\ReflectionClass $class) |
|
367 | { |
||
368 | //Calculamos los dominios para las plantillas |
||
369 | 1 | if ($class->hasConstant("DOMAIN") && !$class->isAbstract()) { |
|
370 | 1 | if (!$this->domains) { |
|
371 | 1 | $this->domains = []; |
|
372 | 1 | } |
|
373 | 1 | $domain = "@" . $class->getConstant("DOMAIN") . "/"; |
|
374 | 1 | if (!array_key_exists($domain, $this->domains)) { |
|
375 | 1 | $this->domains[$domain] = RouterHelper::extractDomainInfo($class, $domain); |
|
376 | 1 | } |
|
377 | 1 | } |
|
378 | |||
379 | 1 | return $this; |
|
380 | } |
||
381 | |||
382 | /** |
||
383 | * Método que genera las urls amigables para usar dentro del framework |
||
384 | * @return Router |
||
385 | */ |
||
386 | 1 | public function simpatize() |
|
387 | { |
||
388 | 1 | $translationFileName = "translations" . DIRECTORY_SEPARATOR . "routes_translations.php"; |
|
389 | 1 | $absoluteTranslationFileName = CACHE_DIR . DIRECTORY_SEPARATOR . $translationFileName; |
|
390 | 1 | $this->generateSlugs($absoluteTranslationFileName); |
|
391 | 1 | GeneratorHelper::createDir(CONFIG_DIR); |
|
392 | 1 | Cache::getInstance()->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . "urls.json", array($this->routing, $this->slugs), Cache::JSON, TRUE); |
|
393 | |||
394 | 1 | return $this; |
|
395 | } |
||
396 | |||
397 | /** |
||
398 | * Método que devuelve una ruta del framework |
||
399 | * |
||
400 | * @param string $slug |
||
401 | * @param boolean $absolute |
||
402 | * @param array $params |
||
403 | * |
||
404 | * @return string|null |
||
405 | * @throws RouterException |
||
406 | */ |
||
407 | 2 | public function getRoute($slug = '', $absolute = FALSE, $params = []) |
|
408 | { |
||
409 | 2 | if (strlen($slug) === 0) { |
|
410 | return ($absolute) ? Request::getInstance()->getRootUrl() . '/' : '/'; |
||
411 | } |
||
412 | 2 | if (!is_array($this->slugs) || !array_key_exists($slug, $this->slugs)) { |
|
413 | throw new RouterException(_("No existe la ruta especificada")); |
||
414 | } |
||
415 | 2 | $url = ($absolute) ? Request::getInstance()->getRootUrl() . $this->slugs[$slug] : $this->slugs[$slug]; |
|
416 | 2 | if (!empty($params)) foreach ($params as $key => $value) { |
|
417 | $url = str_replace("{" . $key . "}", $value, $url); |
||
418 | 2 | } elseif (!empty($this->routing[$this->slugs[$slug]]["default"])) { |
|
419 | 2 | $url = ($absolute) ? Request::getInstance()->getRootUrl() . $this->routing[$this->slugs[$slug]]["default"] : $this->routing[$this->slugs[$slug]]["default"]; |
|
420 | 2 | } |
|
421 | |||
422 | 2 | return preg_replace('/(GET|POST|PUT|DELETE|ALL)\#\|\#/', '', $url); |
|
423 | } |
||
424 | |||
425 | /** |
||
426 | * Método que devuelve las rutas de administración |
||
427 | * @deprecated |
||
428 | * @return array |
||
429 | */ |
||
430 | public function getAdminRoutes() |
||
431 | { |
||
432 | return AdminHelper::getAdminRoutes($this->routing); |
||
433 | } |
||
434 | |||
435 | /** |
||
436 | * Método que devuelve le controlador del admin |
||
437 | * @deprecated |
||
438 | * @return Admin |
||
439 | */ |
||
440 | public function getAdmin() |
||
441 | { |
||
442 | return Admin::getInstance(); |
||
443 | } |
||
444 | |||
445 | /** |
||
446 | * Método que extrae los dominios |
||
447 | * @return array |
||
448 | */ |
||
449 | 1 | public function getDomains() |
|
450 | { |
||
451 | 1 | return $this->domains ?: []; |
|
452 | } |
||
453 | |||
454 | /** |
||
455 | * Método que ejecuta una acción del framework y revisa si lo tenemos cacheado ya o no |
||
456 | * |
||
457 | * @param string $route |
||
458 | * @param array|null $action |
||
459 | * @param types\Controller $class |
||
460 | * @param array $params |
||
461 | */ |
||
462 | protected function executeCachedRoute($route, $action, $class, $params = NULL) |
||
463 | { |
||
464 | Logger::log('Executing route ' . $route, LOG_INFO); |
||
465 | Security::getInstance()->setSessionKey("__CACHE__", $action); |
||
466 | $cache = Cache::needCache(); |
||
467 | $execute = TRUE; |
||
468 | if (FALSE !== $cache && Config::getInstance()->getDebugMode() === FALSE) { |
||
469 | list($path, $cacheDataName) = $this->cache->getRequestCacheHash(); |
||
470 | $cachedData = $this->cache->readFromCache("json" . DIRECTORY_SEPARATOR . $path . $cacheDataName, |
||
471 | $cache, function () { |
||
472 | }); |
||
473 | if (NULL !== $cachedData) { |
||
474 | $headers = $this->cache->readFromCache("json" . DIRECTORY_SEPARATOR . $path . $cacheDataName . ".headers", |
||
475 | $cache, function () { |
||
476 | }, Cache::JSON); |
||
477 | Template::getInstance()->renderCache($cachedData, $headers); |
||
478 | $execute = FALSE; |
||
479 | } |
||
480 | } |
||
481 | if ($execute) { |
||
482 | Logger::log(_('Start executing action'), LOG_DEBUG); |
||
483 | if (false === call_user_func_array(array($class, $action['method']), $params)) { |
||
484 | Logger::log(_('An error ocurred trying to execute the action'), LOG_ERR, [error_get_last()]); |
||
485 | } |
||
486 | } |
||
487 | } |
||
488 | |||
489 | /** |
||
490 | * Parse slugs to create translations |
||
491 | * |
||
492 | * @param string $absoluteTranslationFileName |
||
493 | */ |
||
494 | 1 | private function generateSlugs($absoluteTranslationFileName) |
|
512 | |||
513 | } |
||
514 |
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.