Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
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 | 4 | public function __construct() |
|
| 65 | { |
||
| 66 | 4 | $this->finder = new Finder(); |
|
| 67 | 4 | $this->cache = Cache::getInstance(); |
|
| 68 | 4 | $this->init(); |
|
| 69 | } |
||
| 70 | |||
| 71 | /** |
||
| 72 | * @throws exception\GeneratorException |
||
| 73 | * @throws ConfigException |
||
| 74 | * @throws \InvalidArgumentException |
||
| 75 | */ |
||
| 76 | 4 | public function init() |
|
| 77 | { |
||
| 78 | 4 | list($this->routing, $this->slugs) = $this->cache->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . 'urls.json', $this->cacheType, TRUE); |
|
| 79 | if (empty($this->routing) || Config::getInstance()->getDebugMode()) { |
||
| 80 | $this->debugLoad(); |
||
| 81 | } else { |
||
| 82 | $this->domains = $this->cache->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . 'domains.json', $this->cacheType, TRUE); |
||
| 83 | } |
||
| 84 | $this->checkExternalModules(false); |
||
| 85 | $this->setLoaded(); |
||
| 86 | } |
||
| 87 | |||
| 88 | /** |
||
| 89 | * @throws exception\GeneratorException |
||
| 90 | * @throws ConfigException |
||
| 91 | * @throws \InvalidArgumentException |
||
| 92 | */ |
||
| 93 | private function debugLoad() { |
||
| 94 | Logger::log('Begin routes load'); |
||
| 95 | $this->hydrateRouting(); |
||
| 96 | $this->simpatize(); |
||
| 97 | Logger::log('End routes load'); |
||
| 98 | } |
||
| 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) |
||
| 130 | |||
| 131 | /** |
||
| 132 | * @return array |
||
| 133 | */ |
||
| 134 | public function getSlugs() |
||
| 135 | { |
||
| 136 | return $this->slugs; |
||
| 137 | } |
||
| 138 | |||
| 139 | /** |
||
| 140 | * @return array |
||
| 141 | */ |
||
| 142 | public function getRoutes() { |
||
| 143 | return $this->routing; |
||
| 144 | } |
||
| 145 | |||
| 146 | /** |
||
| 147 | * Method that extract all routes in the platform |
||
| 148 | * @return array |
||
| 149 | */ |
||
| 150 | public function getAllRoutes() |
||
| 151 | { |
||
| 152 | $routes = []; |
||
| 153 | foreach ($this->getRoutes() as $path => $route) { |
||
| 154 | if (array_key_exists('slug', $route)) { |
||
| 155 | $routes[$route['slug']] = $path; |
||
| 156 | } |
||
| 157 | } |
||
| 158 | return $routes; |
||
| 159 | } |
||
| 160 | |||
| 161 | /** |
||
| 162 | * @param string|null $route |
||
| 163 | * |
||
| 164 | * @throws \Exception |
||
| 165 | * @return string HTML |
||
| 166 | */ |
||
| 167 | public function execute($route) |
||
| 168 | { |
||
| 169 | Logger::log('Executing the request'); |
||
| 170 | try { |
||
| 171 | //Search action and execute |
||
| 172 | $this->searchAction($route); |
||
| 173 | } 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 | } catch (RouterException $r) { |
||
| 177 | Logger::log($r->getMessage(), LOG_WARNING); |
||
| 178 | } catch (\Exception $e) { |
||
| 179 | Logger::log($e->getMessage(), LOG_ERR); |
||
| 180 | throw $e; |
||
| 181 | } |
||
| 182 | |||
| 183 | 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 | protected function searchAction($route) |
||
| 194 | { |
||
| 195 | Logger::log('Searching action to execute: ' . $route, LOG_INFO); |
||
| 196 | //Revisamos si tenemos la ruta registrada |
||
| 197 | $parts = parse_url($route); |
||
| 198 | $path = array_key_exists('path', $parts) ? $parts['path'] : $route; |
||
| 199 | $httpRequest = Request::getInstance()->getMethod(); |
||
| 200 | foreach ($this->routing as $pattern => $action) { |
||
| 201 | list($httpMethod, $routePattern) = RouterHelper::extractHttpRoute($pattern); |
||
| 202 | $matched = RouterHelper::matchRoutePattern($routePattern, $path); |
||
| 203 | 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 | throw $e; |
||
| 218 | } |
||
| 219 | } |
||
| 220 | } |
||
| 221 | 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 = []) { |
||
| 243 | |||
| 244 | /** |
||
| 245 | * @return string HTML |
||
| 246 | */ |
||
| 247 | protected function sentAuthHeader() |
||
| 251 | |||
| 252 | /** |
||
| 253 | * @return string|null |
||
| 254 | */ |
||
| 255 | private function getExternalModules() { |
||
| 256 | $externalModules = Config::getParam('modules.extend', ''); |
||
| 257 | $externalModules .= ',psfs/auth'; |
||
| 258 | return $externalModules; |
||
| 259 | } |
||
| 260 | |||
| 261 | /** |
||
| 262 | * @param boolean $hydrateRoute |
||
| 263 | */ |
||
| 264 | private function checkExternalModules($hydrateRoute = true) |
||
| 265 | { |
||
| 266 | $externalModules = $this->getExternalModules(); |
||
| 267 | if ('' !== $externalModules) { |
||
| 268 | $externalModules = explode(',', $externalModules); |
||
| 269 | foreach ($externalModules as &$module) { |
||
| 270 | $module = $this->loadExternalModule($hydrateRoute, $module); |
||
| 271 | } |
||
| 272 | } |
||
| 273 | } |
||
| 274 | |||
| 275 | /** |
||
| 276 | * @throws exception\GeneratorException |
||
| 277 | * @throws ConfigException |
||
| 278 | * @throws \InvalidArgumentException |
||
| 279 | */ |
||
| 280 | private function generateRouting() |
||
| 281 | { |
||
| 282 | $base = SOURCE_DIR; |
||
| 283 | $modulesPath = realpath(CORE_DIR); |
||
| 284 | $this->routing = $this->inspectDir($base, 'PSFS', array()); |
||
| 285 | $this->checkExternalModules(); |
||
| 286 | 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 | $this->cache->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . 'domains.json', $this->domains, Cache::JSON, TRUE); |
||
| 296 | } |
||
| 297 | |||
| 298 | /** |
||
| 299 | * @throws exception\GeneratorException |
||
| 300 | * @throws ConfigException |
||
| 301 | * @throws \InvalidArgumentException |
||
| 302 | */ |
||
| 303 | public function hydrateRouting() |
||
| 304 | { |
||
| 305 | $this->generateRouting(); |
||
| 306 | $home = Config::getParam('home.action'); |
||
| 307 | if (NULL !== $home || $home !== '') { |
||
| 308 | $home_params = NULL; |
||
| 309 | foreach ($this->routing as $pattern => $params) { |
||
| 310 | list($method, $route) = RouterHelper::extractHttpRoute($pattern); |
||
| 311 | if (preg_match('/' . preg_quote($route, '/') . '$/i', '/' . $home)) { |
||
| 312 | $home_params = $params; |
||
| 313 | } |
||
| 314 | } |
||
| 315 | if (NULL !== $home_params) { |
||
| 316 | $this->routing['/'] = $home_params; |
||
| 317 | } |
||
| 318 | } |
||
| 319 | } |
||
| 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 | private function inspectDir($origen, $namespace = 'PSFS', $routing = []) |
||
| 330 | { |
||
| 331 | $files = $this->finder->files()->in($origen)->path('/(controller|api)/i')->depth(1)->name('*.php'); |
||
| 332 | if($files->hasResults()) { |
||
| 333 | foreach ($files->getIterator() as $file) { |
||
| 334 | if(method_exists($file, 'getRelativePathname') && $namespace !== 'PSFS') { |
||
| 335 | $filename = '\\' . str_replace('/', '\\', str_replace($origen, '', $file->getRelativePathname())); |
||
| 336 | } else { |
||
| 337 | $filename = str_replace('/', '\\', str_replace($origen, '', $file->getPathname())); |
||
| 338 | } |
||
| 339 | $routing = $this->addRouting($namespace . str_replace('.php', '', $filename), $routing, $namespace); |
||
| 340 | } |
||
| 341 | } |
||
| 342 | $this->finder = new Finder(); |
||
| 343 | |||
| 344 | return $routing; |
||
| 345 | } |
||
| 346 | |||
| 347 | /** |
||
| 348 | * @param string $namespace |
||
| 349 | * @return bool |
||
| 350 | */ |
||
| 351 | 1 | public static function exists($namespace) |
|
| 355 | |||
| 356 | /** |
||
| 357 | * |
||
| 358 | * @param string $namespace |
||
| 359 | * @param array $routing |
||
| 360 | * @param string $module |
||
| 361 | * |
||
| 362 | * @return array |
||
| 363 | * @throws ConfigException |
||
| 364 | */ |
||
| 365 | private function addRouting($namespace, &$routing, $module = 'PSFS') |
||
| 366 | { |
||
| 367 | if (self::exists($namespace)) { |
||
| 368 | if(I18nHelper::checkI18Class($namespace)) { |
||
| 369 | return $routing; |
||
| 370 | } |
||
| 371 | $reflection = new \ReflectionClass($namespace); |
||
| 372 | if (FALSE === $reflection->isAbstract() && FALSE === $reflection->isInterface()) { |
||
| 373 | $this->extractDomain($reflection); |
||
| 374 | $classComments = $reflection->getDocComment(); |
||
| 375 | preg_match('/@api\ (.*)\n/im', $classComments, $apiPath); |
||
| 376 | $api = ''; |
||
| 377 | if (count($apiPath)) { |
||
| 378 | $api = array_key_exists(1, $apiPath) ? $apiPath[1] : $api; |
||
| 379 | } |
||
| 380 | foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { |
||
| 381 | if (preg_match('/@route\ /i', $method->getDocComment())) { |
||
| 382 | list($route, $info) = RouterHelper::extractRouteInfo($method, str_replace('\\', '', $api), str_replace('\\', '', $module)); |
||
| 383 | |||
| 384 | if (null !== $route && null !== $info) { |
||
| 385 | $info['class'] = $namespace; |
||
| 386 | $routing[$route] = $info; |
||
| 387 | } |
||
| 388 | } |
||
| 389 | } |
||
| 390 | } |
||
| 391 | } |
||
| 392 | |||
| 393 | return $routing; |
||
| 394 | } |
||
| 395 | |||
| 396 | /** |
||
| 397 | * |
||
| 398 | * @param \ReflectionClass $class |
||
| 399 | * |
||
| 400 | * @return Router |
||
| 401 | * @throws ConfigException |
||
| 402 | */ |
||
| 403 | protected function extractDomain(\ReflectionClass $class) |
||
| 404 | { |
||
| 405 | //Calculamos los dominios para las plantillas |
||
| 406 | if ($class->hasConstant('DOMAIN') && !$class->isAbstract()) { |
||
| 407 | if (!$this->domains) { |
||
| 408 | $this->domains = []; |
||
| 409 | } |
||
| 410 | $domain = '@' . $class->getConstant('DOMAIN') . '/'; |
||
| 411 | if (!array_key_exists($domain, $this->domains)) { |
||
| 412 | $this->domains[$domain] = RouterHelper::extractDomainInfo($class, $domain); |
||
| 413 | } |
||
| 414 | } |
||
| 415 | |||
| 416 | return $this; |
||
| 417 | } |
||
| 418 | |||
| 419 | /** |
||
| 420 | * @return $this |
||
| 421 | * @throws exception\GeneratorException |
||
| 422 | * @throws ConfigException |
||
| 423 | */ |
||
| 424 | public function simpatize() |
||
| 425 | { |
||
| 426 | $translationFileName = 'translations' . DIRECTORY_SEPARATOR . 'routes_translations.php'; |
||
| 427 | $absoluteTranslationFileName = CACHE_DIR . DIRECTORY_SEPARATOR . $translationFileName; |
||
| 428 | $this->generateSlugs($absoluteTranslationFileName); |
||
| 429 | GeneratorHelper::createDir(CONFIG_DIR); |
||
| 430 | Cache::getInstance()->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . 'urls.json', array($this->routing, $this->slugs), Cache::JSON, TRUE); |
||
| 431 | |||
| 432 | return $this; |
||
| 433 | } |
||
| 434 | |||
| 435 | /** |
||
| 436 | * @param string $slug |
||
| 437 | * @param boolean $absolute |
||
| 438 | * @param array $params |
||
| 439 | * |
||
| 440 | * @return string|null |
||
| 441 | * @throws RouterException |
||
| 442 | */ |
||
| 443 | public function getRoute($slug = '', $absolute = FALSE, array $params = []) |
||
| 444 | { |
||
| 445 | if ('' === $slug) { |
||
| 446 | return $absolute ? Request::getInstance()->getRootUrl() . '/' : '/'; |
||
| 447 | } |
||
| 448 | if (!is_array($this->slugs) || !array_key_exists($slug, $this->slugs)) { |
||
| 449 | throw new RouterException(_('No existe la ruta especificada')); |
||
| 450 | } |
||
| 451 | $url = $absolute ? Request::getInstance()->getRootUrl() . $this->slugs[$slug] : $this->slugs[$slug]; |
||
| 452 | if (!empty($params)) { |
||
| 453 | foreach ($params as $key => $value) { |
||
| 454 | $url = str_replace('{' . $key . '}', $value, $url); |
||
| 455 | } |
||
| 456 | } elseif (!empty($this->routing[$this->slugs[$slug]]['default'])) { |
||
| 457 | $url = $absolute ? Request::getInstance()->getRootUrl() . $this->routing[$this->slugs[$slug]]['default'] : $this->routing[$this->slugs[$slug]]['default']; |
||
| 458 | } |
||
| 459 | |||
| 460 | return preg_replace('/(GET|POST|PUT|DELETE|ALL)\#\|\#/', '', $url); |
||
| 461 | } |
||
| 462 | |||
| 463 | /** |
||
| 464 | * @deprecated |
||
| 465 | * @return array |
||
| 466 | */ |
||
| 467 | public function getAdminRoutes() |
||
| 471 | |||
| 472 | /** |
||
| 473 | * @deprecated |
||
| 474 | * @return Admin |
||
| 475 | */ |
||
| 476 | public function getAdmin() |
||
| 480 | |||
| 481 | /** |
||
| 482 | * @return array |
||
| 483 | */ |
||
| 484 | public function getDomains() |
||
| 485 | { |
||
| 486 | return $this->domains ?: []; |
||
| 487 | } |
||
| 488 | |||
| 489 | /** |
||
| 490 | * @param string $class |
||
| 491 | * @param string $method |
||
| 492 | */ |
||
| 493 | private function checkPreActions($class, $method) { |
||
| 507 | |||
| 508 | /** |
||
| 509 | * @param string $route |
||
| 510 | * @param array $action |
||
| 511 | * @param string $class |
||
| 512 | * @param array $params |
||
| 513 | * @throws exception\GeneratorException |
||
| 514 | * @throws ConfigException |
||
| 515 | */ |
||
| 516 | protected function executeCachedRoute($route, $action, $class, $params = NULL) |
||
| 540 | |||
| 541 | /** |
||
| 542 | * Parse slugs to create translations |
||
| 543 | * |
||
| 544 | * @param string $absoluteTranslationFileName |
||
| 545 | */ |
||
| 546 | private function generateSlugs($absoluteTranslationFileName) |
||
| 547 | { |
||
| 548 | $translations = I18nHelper::generateTranslationsFile($absoluteTranslationFileName); |
||
| 549 | foreach ($this->routing as $key => &$info) { |
||
| 550 | $keyParts = explode('#|#', $key); |
||
| 551 | $keyParts = array_key_exists(1, $keyParts) ? $keyParts[1] : $keyParts[0]; |
||
| 552 | $slug = RouterHelper::slugify($keyParts); |
||
| 553 | if (NULL !== $slug && !array_key_exists($slug, $translations)) { |
||
| 554 | $translations[$slug] = $info['label']; |
||
| 555 | file_put_contents($absoluteTranslationFileName, "\$translations[\"{$slug}\"] = _(\"{$info['label']}\");\n", FILE_APPEND); |
||
| 556 | } |
||
| 557 | $this->slugs[$slug] = $key; |
||
| 558 | $info['slug'] = $slug; |
||
| 559 | } |
||
| 560 | } |
||
| 561 | |||
| 562 | /** |
||
| 563 | * @param bool $hydrateRoute |
||
| 564 | * @param $modulePath |
||
| 565 | * @param $externalModulePath |
||
| 566 | */ |
||
| 567 | private function loadExternalAutoloader($hydrateRoute, SplFileInfo $modulePath, $externalModulePath) |
||
| 578 | |||
| 579 | /** |
||
| 580 | * @param $hydrateRoute |
||
| 581 | * @param $module |
||
| 582 | * @return mixed |
||
| 583 | */ |
||
| 584 | private function loadExternalModule($hydrateRoute, $module) |
||
| 585 | { |
||
| 586 | try { |
||
| 587 | $module = preg_replace('/(\\\|\/)/', DIRECTORY_SEPARATOR, $module); |
||
| 588 | $externalModulePath = VENDOR_DIR . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . 'src'; |
||
| 589 | if(file_exists($externalModulePath)) { |
||
| 590 | $externalModule = $this->finder->directories()->in($externalModulePath)->depth(0); |
||
| 591 | if($externalModule->hasResults()) { |
||
| 592 | foreach ($externalModule->getIterator() as $modulePath) { |
||
| 593 | $this->loadExternalAutoloader($hydrateRoute, $modulePath, $externalModulePath); |
||
| 594 | } |
||
| 595 | } |
||
| 596 | } |
||
| 597 | } catch (\Exception $e) { |
||
| 603 | |||
| 604 | } |
||
| 605 |
It seems like the type of the argument is not accepted by the function/method which you are calling.
In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.
We suggest to add an explicit type cast like in the following example: