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