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 |
||
25 | class Router |
||
26 | { |
||
27 | use SingletonTrait; |
||
28 | |||
29 | /** |
||
30 | * @var array |
||
31 | */ |
||
32 | protected $routing = []; |
||
33 | /** |
||
34 | * @var array |
||
35 | */ |
||
36 | protected $slugs = []; |
||
37 | /** |
||
38 | * @var array |
||
39 | */ |
||
40 | private $domains = []; |
||
41 | /** |
||
42 | * @var Finder $finder |
||
43 | */ |
||
44 | private $finder; |
||
45 | /** |
||
46 | * @var \PSFS\base\Cache $cache |
||
47 | */ |
||
48 | private $cache; |
||
49 | /** |
||
50 | * @var bool headersSent |
||
51 | */ |
||
52 | protected $headersSent = false; |
||
53 | /** |
||
54 | * @var int |
||
55 | */ |
||
56 | protected $cacheType = Cache::JSON; |
||
57 | |||
58 | /** |
||
59 | * Router constructor. |
||
60 | * @throws exception\GeneratorException |
||
61 | * @throws ConfigException |
||
62 | * @throws \InvalidArgumentException |
||
63 | */ |
||
64 | 1 | public function __construct() |
|
65 | { |
||
66 | 1 | $this->finder = new Finder(); |
|
67 | 1 | $this->cache = Cache::getInstance(); |
|
68 | 1 | $this->init(); |
|
69 | 1 | } |
|
70 | |||
71 | /** |
||
72 | * @throws exception\GeneratorException |
||
73 | * @throws ConfigException |
||
74 | * @throws \InvalidArgumentException |
||
75 | */ |
||
76 | 1 | public function init() |
|
77 | { |
||
78 | 1 | list($this->routing, $this->slugs) = $this->cache->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . 'urls.json', $this->cacheType, TRUE); |
|
|
|||
79 | 1 | if (empty($this->routing) || Config::getInstance()->getDebugMode()) { |
|
80 | 1 | $this->debugLoad(); |
|
81 | } else { |
||
82 | $this->domains = $this->cache->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . 'domains.json', $this->cacheType, TRUE); |
||
83 | } |
||
84 | 1 | $this->checkExternalModules(false); |
|
85 | 1 | $this->setLoaded(); |
|
86 | 1 | } |
|
87 | |||
88 | /** |
||
89 | * @throws exception\GeneratorException |
||
90 | * @throws ConfigException |
||
91 | * @throws \InvalidArgumentException |
||
92 | */ |
||
93 | 1 | private function debugLoad() { |
|
94 | 1 | Logger::log('Begin routes load'); |
|
95 | 1 | $this->hydrateRouting(); |
|
96 | 1 | $this->simpatize(); |
|
97 | 1 | Logger::log('End routes load'); |
|
98 | 1 | } |
|
99 | |||
100 | /** |
||
101 | * @param \Exception|NULL $e |
||
102 | * @param bool $isJson |
||
103 | * @return string |
||
104 | * @throws RouterException |
||
105 | */ |
||
106 | public function httpNotFound(\Exception $e = NULL, $isJson = false) |
||
107 | { |
||
108 | Logger::log('Throw not found exception'); |
||
109 | if (NULL === $e) { |
||
110 | Logger::log('Not found page thrown without previous exception', LOG_WARNING); |
||
111 | $e = new \Exception(_('Page not found'), 404); |
||
112 | } |
||
113 | $template = Template::getInstance()->setStatus($e->getCode()); |
||
114 | if ($isJson || false !== stripos(Request::getInstance()->getServer('CONTENT_TYPE'), 'json')) { |
||
115 | $response = new JsonResponse(null, false, 0, 0, $e->getMessage()); |
||
116 | return $template->output(json_encode($response), 'application/json'); |
||
117 | } |
||
118 | |||
119 | $not_found_route = Config::getParam('route.404'); |
||
120 | if(null !== $not_found_route) { |
||
121 | Request::getInstance()->redirect($this->getRoute($not_found_route, true)); |
||
122 | } else { |
||
123 | return $template->render('error.html.twig', array( |
||
124 | 'exception' => $e, |
||
125 | 'trace' => $e->getTraceAsString(), |
||
126 | 'error_page' => TRUE, |
||
127 | )); |
||
128 | } |
||
129 | } |
||
130 | |||
131 | /** |
||
132 | * @return array |
||
133 | */ |
||
134 | 1 | public function getSlugs() |
|
135 | { |
||
136 | 1 | return $this->slugs; |
|
137 | } |
||
138 | |||
139 | /** |
||
140 | * @return array |
||
141 | */ |
||
142 | 2 | public function getRoutes() { |
|
143 | 2 | return $this->routing; |
|
144 | } |
||
145 | |||
146 | /** |
||
147 | * Method that extract all routes in the platform |
||
148 | * @return array |
||
149 | */ |
||
150 | 1 | public function getAllRoutes() |
|
151 | { |
||
152 | 1 | $routes = []; |
|
153 | 1 | foreach ($this->getRoutes() as $path => $route) { |
|
154 | 1 | if (array_key_exists('slug', $route)) { |
|
155 | 1 | $routes[$route['slug']] = $path; |
|
156 | } |
||
157 | } |
||
158 | 1 | return $routes; |
|
159 | } |
||
160 | |||
161 | /** |
||
162 | * @param string|null $route |
||
163 | * |
||
164 | * @throws \Exception |
||
165 | * @return string HTML |
||
166 | */ |
||
167 | 1 | public function execute($route) |
|
168 | { |
||
169 | 1 | Logger::log('Executing the request'); |
|
170 | try { |
||
171 | //Search action and execute |
||
172 | 1 | $this->searchAction($route); |
|
173 | 1 | } catch (AccessDeniedException $e) { |
|
174 | Logger::log(_('Solicitamos credenciales de acceso a zona restringida'), LOG_WARNING, ['file' => $e->getFile() . '[' . $e->getLine() . ']']); |
||
175 | return Admin::staticAdminLogon($route); |
||
176 | 1 | } catch (RouterException $r) { |
|
177 | 1 | Logger::log($r->getMessage(), LOG_WARNING); |
|
178 | } catch (\Exception $e) { |
||
179 | Logger::log($e->getMessage(), LOG_ERR); |
||
180 | throw $e; |
||
181 | } |
||
182 | |||
183 | 1 | throw new RouterException(_('Página no encontrada'), 404); |
|
184 | } |
||
185 | |||
186 | /** |
||
187 | * @param $route |
||
188 | * @throws AccessDeniedException |
||
189 | * @throws AdminCredentialsException |
||
190 | * @throws RouterException |
||
191 | * @throws \Exception |
||
192 | */ |
||
193 | 1 | protected function searchAction($route) |
|
194 | { |
||
195 | 1 | Logger::log('Searching action to execute: ' . $route, LOG_INFO); |
|
196 | //Revisamos si tenemos la ruta registrada |
||
197 | 1 | $parts = parse_url($route); |
|
198 | 1 | $path = array_key_exists('path', $parts) ? $parts['path'] : $route; |
|
199 | 1 | $httpRequest = Request::getInstance()->getMethod(); |
|
200 | 1 | foreach ($this->routing as $pattern => $action) { |
|
201 | 1 | list($httpMethod, $routePattern) = RouterHelper::extractHttpRoute($pattern); |
|
202 | 1 | $matched = RouterHelper::matchRoutePattern($routePattern, $path); |
|
203 | 1 | if ($matched && ($httpMethod === 'ALL' || $httpRequest === $httpMethod) && RouterHelper::compareSlashes($routePattern, $path)) { |
|
204 | // Checks restricted access |
||
205 | SecurityHelper::checkRestrictedAccess($route); |
||
206 | $get = RouterHelper::extractComponents($route, $routePattern); |
||
207 | /** @var $class \PSFS\base\types\Controller */ |
||
208 | $class = RouterHelper::getClassToCall($action); |
||
209 | try { |
||
210 | if($this->checkRequirements($action, $get)) { |
||
211 | $this->executeCachedRoute($route, $action, $class, $get); |
||
212 | } else { |
||
213 | throw new RouterException(_('La ruta no es válida'), 400); |
||
214 | } |
||
215 | } catch (\Exception $e) { |
||
216 | Logger::log($e->getMessage(), LOG_ERR); |
||
217 | 1 | throw $e; |
|
218 | } |
||
219 | } |
||
220 | } |
||
221 | 1 | throw new RouterException(_('Ruta no encontrada')); |
|
222 | } |
||
223 | |||
224 | /** |
||
225 | * @param array $action |
||
226 | * @param array $params |
||
227 | * @return bool |
||
228 | */ |
||
229 | private function checkRequirements(array $action, $params = []) { |
||
230 | if(!empty($params) && !empty($action['requirements'])) { |
||
231 | $checked = 0; |
||
232 | foreach(array_keys($params) as $key) { |
||
233 | if(in_array($key, $action['requirements'], true)) { |
||
234 | $checked++; |
||
235 | } |
||
236 | } |
||
237 | $valid = count($action['requirements']) === $checked; |
||
238 | } else { |
||
239 | $valid = true; |
||
240 | } |
||
241 | return $valid; |
||
242 | } |
||
243 | |||
244 | /** |
||
245 | * @return string HTML |
||
246 | */ |
||
247 | protected function sentAuthHeader() |
||
251 | |||
252 | /** |
||
253 | * @return string|null |
||
254 | */ |
||
255 | 1 | private function getExternalModules() { |
|
256 | 1 | $externalModules = Config::getParam('modules.extend', ''); |
|
257 | 1 | $externalModules .= ',psfs/auth'; |
|
258 | 1 | return $externalModules; |
|
259 | } |
||
260 | |||
261 | /** |
||
262 | * @param boolean $hydrateRoute |
||
263 | */ |
||
264 | 1 | private function checkExternalModules($hydrateRoute = true) |
|
265 | { |
||
266 | 1 | $externalModules = $this->getExternalModules(); |
|
267 | 1 | if ('' !== $externalModules) { |
|
268 | 1 | $externalModules = explode(',', $externalModules); |
|
269 | 1 | foreach ($externalModules as &$module) { |
|
270 | 1 | $module = $this->loadExternalModule($hydrateRoute, $module); |
|
271 | } |
||
272 | } |
||
273 | 1 | } |
|
274 | |||
275 | /** |
||
276 | * @throws exception\GeneratorException |
||
277 | * @throws ConfigException |
||
278 | * @throws \InvalidArgumentException |
||
279 | */ |
||
280 | 1 | private function generateRouting() |
|
281 | { |
||
282 | 1 | $base = SOURCE_DIR; |
|
283 | 1 | $modulesPath = realpath(CORE_DIR); |
|
284 | 1 | $this->routing = $this->inspectDir($base, 'PSFS', array()); |
|
285 | 1 | $this->checkExternalModules(); |
|
286 | 1 | if (file_exists($modulesPath)) { |
|
287 | $modules = $this->finder->directories()->in($modulesPath)->depth(0); |
||
288 | if($modules->hasResults()) { |
||
289 | foreach ($modules->getIterator() as $modulePath) { |
||
290 | $module = $modulePath->getBasename(); |
||
291 | $this->routing = $this->inspectDir($modulesPath . DIRECTORY_SEPARATOR . $module, $module, $this->routing); |
||
292 | } |
||
293 | } |
||
294 | } |
||
295 | 1 | $this->cache->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . 'domains.json', $this->domains, Cache::JSON, TRUE); |
|
296 | 1 | } |
|
297 | |||
298 | /** |
||
299 | * @throws exception\GeneratorException |
||
300 | * @throws ConfigException |
||
301 | * @throws \InvalidArgumentException |
||
302 | */ |
||
303 | 1 | public function hydrateRouting() |
|
304 | { |
||
305 | 1 | $this->generateRouting(); |
|
306 | 1 | $home = Config::getParam('home.action'); |
|
307 | 1 | if (NULL !== $home || $home !== '') { |
|
308 | 1 | $home_params = NULL; |
|
309 | 1 | foreach ($this->routing as $pattern => $params) { |
|
310 | 1 | list($method, $route) = RouterHelper::extractHttpRoute($pattern); |
|
311 | 1 | if (preg_match('/' . preg_quote($route, '/') . '$/i', '/' . $home)) { |
|
312 | 1 | $home_params = $params; |
|
313 | } |
||
314 | } |
||
315 | 1 | if (NULL !== $home_params) { |
|
316 | $this->routing['/'] = $home_params; |
||
317 | } |
||
318 | } |
||
319 | 1 | } |
|
320 | |||
321 | /** |
||
322 | * @param string $origen |
||
323 | * @param string $namespace |
||
324 | * @param array $routing |
||
325 | * @return array |
||
326 | * @throws ConfigException |
||
327 | * @throws \InvalidArgumentException |
||
328 | */ |
||
329 | 1 | private function inspectDir($origen, $namespace = 'PSFS', $routing = []) |
|
330 | { |
||
331 | 1 | $files = $this->finder->files()->in($origen)->path('/(controller|api)/i')->depth(1)->name('*.php'); |
|
332 | 1 | if($files->hasResults()) { |
|
333 | 1 | foreach ($files->getIterator() as $file) { |
|
334 | 1 | $filename = str_replace('/', '\\', str_replace($origen, '', $file->getPathname())); |
|
335 | 1 | $routing = $this->addRouting($namespace . str_replace('.php', '', $filename), $routing, $namespace); |
|
336 | } |
||
337 | } |
||
338 | 1 | $this->finder = new Finder(); |
|
339 | |||
340 | 1 | return $routing; |
|
341 | } |
||
342 | |||
343 | /** |
||
344 | * @param string $namespace |
||
345 | * @return bool |
||
346 | */ |
||
347 | 3 | public static function exists($namespace) |
|
348 | { |
||
349 | 3 | return (class_exists($namespace) || interface_exists($namespace) || trait_exists($namespace)); |
|
350 | } |
||
351 | |||
352 | /** |
||
353 | * |
||
354 | * @param string $namespace |
||
355 | * @param array $routing |
||
356 | * @param string $module |
||
357 | * |
||
358 | * @return array |
||
359 | * @throws ConfigException |
||
360 | */ |
||
361 | 1 | private function addRouting($namespace, &$routing, $module = 'PSFS') |
|
362 | { |
||
363 | 1 | if (self::exists($namespace)) { |
|
364 | 1 | if(I18nHelper::checkI18Class($namespace)) { |
|
365 | return $routing; |
||
366 | } |
||
367 | 1 | $reflection = new \ReflectionClass($namespace); |
|
368 | 1 | if (FALSE === $reflection->isAbstract() && FALSE === $reflection->isInterface()) { |
|
369 | 1 | $this->extractDomain($reflection); |
|
370 | 1 | $classComments = $reflection->getDocComment(); |
|
371 | 1 | preg_match('/@api\ (.*)\n/im', $classComments, $apiPath); |
|
372 | 1 | $api = ''; |
|
373 | 1 | if (count($apiPath)) { |
|
374 | $api = array_key_exists(1, $apiPath) ? $apiPath[1] : $api; |
||
375 | } |
||
376 | 1 | foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { |
|
377 | 1 | if (preg_match('/@route\ /i', $method->getDocComment())) { |
|
378 | 1 | list($route, $info) = RouterHelper::extractRouteInfo($method, str_replace('\\', '', $api), str_replace('\\', '', $module)); |
|
379 | |||
380 | 1 | if (null !== $route && null !== $info) { |
|
381 | 1 | $info['class'] = $namespace; |
|
382 | 1 | $routing[$route] = $info; |
|
383 | } |
||
384 | } |
||
385 | } |
||
386 | } |
||
387 | } |
||
388 | |||
389 | 1 | return $routing; |
|
390 | } |
||
391 | |||
392 | /** |
||
393 | * |
||
394 | * @param \ReflectionClass $class |
||
395 | * |
||
396 | * @return Router |
||
397 | * @throws ConfigException |
||
398 | */ |
||
399 | 1 | protected function extractDomain(\ReflectionClass $class) |
|
400 | { |
||
401 | //Calculamos los dominios para las plantillas |
||
402 | 1 | if ($class->hasConstant('DOMAIN') && !$class->isAbstract()) { |
|
403 | 1 | if (!$this->domains) { |
|
404 | 1 | $this->domains = []; |
|
405 | } |
||
406 | 1 | $domain = '@' . $class->getConstant('DOMAIN') . '/'; |
|
407 | 1 | if (!array_key_exists($domain, $this->domains)) { |
|
408 | 1 | $this->domains[$domain] = RouterHelper::extractDomainInfo($class, $domain); |
|
409 | } |
||
410 | } |
||
411 | |||
412 | 1 | return $this; |
|
413 | } |
||
414 | |||
415 | /** |
||
416 | * @return $this |
||
417 | * @throws exception\GeneratorException |
||
418 | * @throws ConfigException |
||
419 | */ |
||
420 | 1 | public function simpatize() |
|
421 | { |
||
422 | 1 | $translationFileName = 'translations' . DIRECTORY_SEPARATOR . 'routes_translations.php'; |
|
423 | 1 | $absoluteTranslationFileName = CACHE_DIR . DIRECTORY_SEPARATOR . $translationFileName; |
|
424 | 1 | $this->generateSlugs($absoluteTranslationFileName); |
|
425 | 1 | GeneratorHelper::createDir(CONFIG_DIR); |
|
426 | 1 | Cache::getInstance()->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . 'urls.json', array($this->routing, $this->slugs), Cache::JSON, TRUE); |
|
427 | |||
428 | 1 | return $this; |
|
429 | } |
||
430 | |||
431 | /** |
||
432 | * @param string $slug |
||
433 | * @param boolean $absolute |
||
434 | * @param array $params |
||
435 | * |
||
436 | * @return string|null |
||
437 | * @throws RouterException |
||
438 | */ |
||
439 | 3 | public function getRoute($slug = '', $absolute = FALSE, array $params = []) |
|
440 | { |
||
441 | 3 | if ('' === $slug) { |
|
442 | 1 | return $absolute ? Request::getInstance()->getRootUrl() . '/' : '/'; |
|
443 | } |
||
444 | 3 | if (!is_array($this->slugs) || !array_key_exists($slug, $this->slugs)) { |
|
445 | 1 | throw new RouterException(_('No existe la ruta especificada')); |
|
446 | } |
||
447 | 3 | $url = $absolute ? Request::getInstance()->getRootUrl() . $this->slugs[$slug] : $this->slugs[$slug]; |
|
448 | 3 | if (!empty($params)) { |
|
449 | foreach ($params as $key => $value) { |
||
450 | $url = str_replace('{' . $key . '}', $value, $url); |
||
451 | } |
||
452 | 3 | } elseif (!empty($this->routing[$this->slugs[$slug]]['default'])) { |
|
453 | 3 | $url = $absolute ? Request::getInstance()->getRootUrl() . $this->routing[$this->slugs[$slug]]['default'] : $this->routing[$this->slugs[$slug]]['default']; |
|
454 | } |
||
455 | |||
456 | 3 | return preg_replace('/(GET|POST|PUT|DELETE|ALL)\#\|\#/', '', $url); |
|
457 | } |
||
458 | |||
459 | /** |
||
460 | * @deprecated |
||
461 | * @return array |
||
462 | */ |
||
463 | public function getAdminRoutes() |
||
464 | { |
||
465 | return AdminHelper::getAdminRoutes($this->routing); |
||
466 | } |
||
467 | |||
468 | /** |
||
469 | * @deprecated |
||
470 | * @return Admin |
||
471 | */ |
||
472 | public function getAdmin() |
||
473 | { |
||
474 | return Admin::getInstance(); |
||
475 | } |
||
476 | |||
477 | /** |
||
478 | * @return array |
||
479 | */ |
||
480 | 1 | public function getDomains() |
|
484 | |||
485 | /** |
||
486 | * @param string $route |
||
487 | * @param array $action |
||
488 | * @param string $class |
||
489 | * @param array $params |
||
490 | * @throws exception\GeneratorException |
||
491 | * @throws ConfigException |
||
492 | */ |
||
493 | protected function executeCachedRoute($route, $action, $class, $params = NULL) |
||
518 | |||
519 | /** |
||
520 | * Parse slugs to create translations |
||
521 | * |
||
522 | * @param string $absoluteTranslationFileName |
||
523 | */ |
||
524 | 1 | private function generateSlugs($absoluteTranslationFileName) |
|
525 | { |
||
526 | 1 | $translations = I18nHelper::generateTranslationsFile($absoluteTranslationFileName); |
|
527 | 1 | foreach ($this->routing as $key => &$info) { |
|
528 | 1 | $keyParts = explode('#|#', $key); |
|
529 | 1 | $keyParts = array_key_exists(1, $keyParts) ? $keyParts[1] : $keyParts[0]; |
|
530 | 1 | $slug = RouterHelper::slugify($keyParts); |
|
531 | 1 | if (NULL !== $slug && !array_key_exists($slug, $translations)) { |
|
532 | 1 | $translations[$slug] = $info['label']; |
|
533 | 1 | file_put_contents($absoluteTranslationFileName, "\$translations[\"{$slug}\"] = _(\"{$info['label']}\");\n", FILE_APPEND); |
|
534 | } |
||
535 | 1 | $this->slugs[$slug] = $key; |
|
536 | 1 | $info['slug'] = $slug; |
|
537 | } |
||
538 | 1 | } |
|
539 | |||
540 | /** |
||
541 | * @param bool $hydrateRoute |
||
542 | * @param $modulePath |
||
543 | * @param $externalModulePath |
||
544 | */ |
||
545 | private function loadExternalAutoloader($hydrateRoute, SplFileInfo $modulePath, $externalModulePath) |
||
556 | |||
557 | /** |
||
558 | * @param $hydrateRoute |
||
559 | * @param $module |
||
560 | * @return mixed |
||
561 | */ |
||
562 | 1 | private function loadExternalModule($hydrateRoute, $module) |
|
579 | |||
580 | } |
||
581 |
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.