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