| Total Complexity | 63 |
| Total Lines | 585 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
Complex classes like Redirects 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.
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 Redirects, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 39 | class Redirects extends Component |
||
| 40 | { |
||
| 41 | // Constants |
||
| 42 | // ========================================================================= |
||
| 43 | |||
| 44 | const CACHE_KEY = 'retour_redirect_'; |
||
| 45 | |||
| 46 | const GLOBAL_REDIRECTS_CACHE_TAG = 'retour_redirects'; |
||
| 47 | |||
| 48 | // Protected Properties |
||
| 49 | // ========================================================================= |
||
| 50 | |||
| 51 | /** |
||
| 52 | * @var null|array |
||
| 53 | */ |
||
| 54 | protected $cachedStaticRedirects; |
||
| 55 | |||
| 56 | // Public Methods |
||
| 57 | // ========================================================================= |
||
| 58 | |||
| 59 | /** |
||
| 60 | * Handle 404s by looking for redirects |
||
| 61 | */ |
||
| 62 | public function handle404() |
||
| 63 | { |
||
| 64 | Craft::info( |
||
| 65 | Craft::t( |
||
| 66 | 'retour', |
||
| 67 | 'A 404 exception occurred' |
||
| 68 | ), |
||
| 69 | __METHOD__ |
||
| 70 | ); |
||
| 71 | $request = Craft::$app->getRequest(); |
||
| 72 | // We only want site requests that are not live preview or console requests |
||
| 73 | if ($request->getIsSiteRequest() && !$request->getIsLivePreview() && !$request->getIsConsoleRequest()) { |
||
| 74 | // See if we should redirect |
||
| 75 | try { |
||
| 76 | $fullUrl = urldecode($request->getAbsoluteUrl()); |
||
| 77 | $pathOnly = urldecode($request->getUrl()); |
||
| 78 | } catch (InvalidConfigException $e) { |
||
| 79 | Craft::error( |
||
| 80 | $e->getMessage(), |
||
| 81 | __METHOD__ |
||
| 82 | ); |
||
| 83 | $pathOnly = ''; |
||
| 84 | $fullUrl = ''; |
||
| 85 | } |
||
| 86 | // Strip the query string if `alwaysStripQueryString` is set |
||
| 87 | if (Retour::$settings->alwaysStripQueryString) { |
||
| 88 | $fullUrl = UrlHelper::stripQueryString($fullUrl); |
||
| 89 | $pathOnly = UrlHelper::stripQueryString($pathOnly); |
||
| 90 | } |
||
| 91 | Craft::info( |
||
| 92 | Craft::t( |
||
| 93 | 'retour', |
||
| 94 | '404 full URL: {fullUrl}, 404 path only: {pathOnly}', |
||
| 95 | ['fullUrl' => $fullUrl, 'pathOnly' => $pathOnly] |
||
| 96 | ), |
||
| 97 | __METHOD__ |
||
| 98 | ); |
||
| 99 | // Redirect if we find a match, otherwise let Craft handle it |
||
| 100 | $redirect = $this->findRedirectMatch($fullUrl, $pathOnly); |
||
| 101 | if (!$this->doRedirect($fullUrl, $pathOnly, $redirect) && !Retour::$settings->alwaysStripQueryString) { |
||
| 102 | // Try it again without the query string |
||
| 103 | $fullUrl = UrlHelper::stripQueryString($fullUrl); |
||
| 104 | $pathOnly = UrlHelper::stripQueryString($pathOnly); |
||
| 105 | $redirect = $this->findRedirectMatch($fullUrl, $pathOnly); |
||
| 106 | $this->doRedirect($fullUrl, $pathOnly, $redirect); |
||
| 107 | } |
||
| 108 | // Increment the stats |
||
| 109 | Retour::$plugin->statistics->incrementStatistics($pathOnly, false); |
||
| 110 | } |
||
| 111 | } |
||
| 112 | |||
| 113 | /** |
||
| 114 | * Do the redirect |
||
| 115 | * |
||
| 116 | * @param string $fullUrl |
||
| 117 | * @param string $pathOnly |
||
| 118 | * @param null|array $redirect |
||
| 119 | * |
||
| 120 | * @return bool false if not redirected |
||
| 121 | */ |
||
| 122 | public function doRedirect(string $fullUrl, string $pathOnly, $redirect): bool |
||
| 123 | { |
||
| 124 | $response = Craft::$app->getResponse(); |
||
| 125 | if ($redirect !== null) { |
||
| 126 | // Figure out what type of source matching was done |
||
| 127 | $redirectSrcMatch = $redirect['redirectSrcMatch'] ?? 'pathonly'; |
||
| 128 | switch ($redirectSrcMatch) { |
||
| 129 | case 'pathonly': |
||
| 130 | $url = $pathOnly; |
||
| 131 | break; |
||
| 132 | case 'fullurl': |
||
| 133 | $url = $fullUrl; |
||
| 134 | break; |
||
| 135 | default: |
||
| 136 | $url = $pathOnly; |
||
| 137 | break; |
||
| 138 | } |
||
| 139 | $dest = $redirect['redirectDestUrl']; |
||
| 140 | if (Retour::$settings->preserveQueryString) { |
||
| 141 | $request = Craft::$app->getRequest(); |
||
| 142 | $dest .= '?' . $request->getQueryString(); |
||
| 143 | } |
||
| 144 | $status = $redirect['redirectHttpCode']; |
||
| 145 | Craft::info( |
||
| 146 | Craft::t( |
||
| 147 | 'retour', |
||
| 148 | 'Redirecting {url} to {dest} with status {status}', |
||
| 149 | ['url' => $url, 'dest' => $dest, 'status' => $status] |
||
| 150 | ), |
||
| 151 | __METHOD__ |
||
| 152 | ); |
||
| 153 | // Increment the stats |
||
| 154 | Retour::$plugin->statistics->incrementStatistics($url, true); |
||
| 155 | // Handle a Retour return status > 400 to render the actual error template |
||
| 156 | if ($status >= 400) { |
||
| 157 | Retour::$currentException->statusCode = $status; |
||
| 158 | $errorHandler = Craft::$app->getErrorHandler(); |
||
| 159 | $errorHandler->exception = Retour::$currentException; |
||
| 160 | try { |
||
| 161 | $response = Craft::$app->runAction('templates/render-error'); |
||
| 162 | } catch (InvalidRouteException $e) { |
||
| 163 | Craft::error($e->getMessage(), __METHOD__); |
||
| 164 | } catch (\yii\console\Exception $e) { |
||
| 165 | Craft::error($e->getMessage(), __METHOD__); |
||
| 166 | } |
||
| 167 | } |
||
| 168 | // Redirect the request away; |
||
| 169 | $response->redirect($dest, $status)->send(); |
||
| 170 | try { |
||
| 171 | Craft::$app->end(); |
||
| 172 | } catch (ExitException $e) { |
||
| 173 | Craft::error($e->getMessage(), __METHOD__); |
||
| 174 | } |
||
| 175 | } |
||
| 176 | |||
| 177 | return false; |
||
| 178 | } |
||
| 179 | |||
| 180 | /** |
||
| 181 | * @param string $fullUrl |
||
| 182 | * @param string $pathOnly |
||
| 183 | * |
||
| 184 | * @return array|null |
||
| 185 | */ |
||
| 186 | public function findRedirectMatch(string $fullUrl, string $pathOnly) |
||
| 187 | { |
||
| 188 | // Try getting the full URL redirect from the cache |
||
| 189 | $redirect = $this->getRedirectFromCache($fullUrl); |
||
| 190 | if ($redirect) { |
||
| 191 | $this->incrementRedirectHitCount($redirect); |
||
| 192 | $this->saveRedirectToCache($fullUrl, $redirect); |
||
| 193 | |||
| 194 | return $redirect; |
||
| 195 | } |
||
| 196 | |||
| 197 | // Try getting the path only redirect from the cache |
||
| 198 | $redirect = $this->getRedirectFromCache($pathOnly); |
||
| 199 | if ($redirect) { |
||
| 200 | $this->incrementRedirectHitCount($redirect); |
||
| 201 | $this->saveRedirectToCache($pathOnly, $redirect); |
||
| 202 | |||
| 203 | return $redirect; |
||
| 204 | } |
||
| 205 | |||
| 206 | // Resolve static redirects |
||
| 207 | $redirects = $this->getAllStaticRedirects(); |
||
| 208 | $redirect = $this->resolveRedirect($fullUrl, $pathOnly, $redirects); |
||
| 209 | if ($redirect) { |
||
| 210 | return $redirect; |
||
| 211 | } |
||
| 212 | |||
| 213 | return null; |
||
| 214 | } |
||
| 215 | |||
| 216 | /** |
||
| 217 | * @param $url |
||
| 218 | * |
||
| 219 | * @return bool|array |
||
| 220 | */ |
||
| 221 | public function getRedirectFromCache($url) |
||
| 236 | } |
||
| 237 | |||
| 238 | /** |
||
| 239 | * @param string $url |
||
| 240 | * @param array $redirect |
||
| 241 | */ |
||
| 242 | public function saveRedirectToCache($url, $redirect) |
||
| 243 | { |
||
| 244 | $cacheKey = $this::CACHE_KEY.md5($url); |
||
| 245 | $cache = Craft::$app->getCache(); |
||
| 246 | // Get the current site id |
||
| 247 | $sites = Craft::$app->getSites(); |
||
| 248 | try { |
||
| 249 | $siteId = $sites->getCurrentSite()->id; |
||
| 250 | } catch (SiteNotFoundException $e) { |
||
| 251 | $siteId = 1; |
||
| 252 | } |
||
| 253 | // Create the dependency tags |
||
| 254 | $dependency = new TagDependency([ |
||
| 255 | 'tags' => [ |
||
| 256 | $this::GLOBAL_REDIRECTS_CACHE_TAG, |
||
| 257 | $this::GLOBAL_REDIRECTS_CACHE_TAG.$siteId, |
||
| 258 | ], |
||
| 259 | ]); |
||
| 260 | $cache->set($cacheKey, $redirect, Retour::$cacheDuration, $dependency); |
||
| 261 | Craft::info( |
||
| 262 | Craft::t( |
||
| 263 | 'retour', |
||
| 264 | 'Cached redirect saved for {url}', |
||
| 265 | ['url' => $url] |
||
| 266 | ), |
||
| 267 | __METHOD__ |
||
| 268 | ); |
||
| 269 | } |
||
| 270 | |||
| 271 | /** |
||
| 272 | * @param string $fullUrl |
||
| 273 | * @param string $pathOnly |
||
| 274 | * @param array $redirects |
||
| 275 | * |
||
| 276 | * @return array|null |
||
| 277 | */ |
||
| 278 | public function resolveRedirect(string $fullUrl, string $pathOnly, array $redirects) |
||
| 279 | { |
||
| 280 | $result = null; |
||
| 281 | foreach ($redirects as $redirect) { |
||
| 282 | // Figure out what type of source matching to do |
||
| 283 | $redirectSrcMatch = $redirect['redirectSrcMatch'] ?? 'pathonly'; |
||
| 284 | $redirectEnabled = (bool)$redirect['enabled']; |
||
| 285 | if ($redirectEnabled === true) { |
||
| 286 | switch ($redirectSrcMatch) { |
||
| 287 | case 'pathonly': |
||
| 288 | $url = $pathOnly; |
||
| 289 | break; |
||
| 290 | case 'fullurl': |
||
| 291 | $url = $fullUrl; |
||
| 292 | break; |
||
| 293 | default: |
||
| 294 | $url = $pathOnly; |
||
| 295 | break; |
||
| 296 | } |
||
| 297 | $redirectMatchType = $redirect['redirectMatchType'] ?? 'notfound'; |
||
| 298 | switch ($redirectMatchType) { |
||
| 299 | // Do a straight up match |
||
| 300 | case 'exactmatch': |
||
| 301 | if (strcasecmp($redirect['redirectSrcUrlParsed'], $url) === 0) { |
||
| 302 | $this->incrementRedirectHitCount($redirect); |
||
| 303 | $this->saveRedirectToCache($url, $redirect); |
||
| 304 | |||
| 305 | return $redirect; |
||
| 306 | } |
||
| 307 | break; |
||
| 308 | |||
| 309 | // Do a regex match |
||
| 310 | case 'regexmatch': |
||
| 311 | $matchRegEx = '`'.$redirect['redirectSrcUrlParsed'].'`i'; |
||
| 312 | if (preg_match($matchRegEx, $url) === 1) { |
||
| 313 | $this->incrementRedirectHitCount($redirect); |
||
| 314 | // If we're not associated with an EntryID, handle capture group replacement |
||
| 315 | if ((int)$redirect['associatedElementId'] === 0) { |
||
| 316 | $redirect['redirectDestUrl'] = preg_replace( |
||
| 317 | $matchRegEx, |
||
| 318 | $redirect['redirectDestUrl'], |
||
| 319 | $url |
||
| 320 | ); |
||
| 321 | } |
||
| 322 | $this->saveRedirectToCache($url, $redirect); |
||
| 323 | |||
| 324 | return $redirect; |
||
| 325 | } |
||
| 326 | break; |
||
| 327 | |||
| 328 | // Otherwise try to look up a plugin's method by and call it for the match |
||
| 329 | default: |
||
| 330 | $plugin = $redirectMatchType ? Craft::$app->getPlugins()->getPlugin($redirectMatchType) : null; |
||
| 331 | if ($plugin && method_exists($plugin, 'retourMatch')) { |
||
| 332 | $args = [ |
||
| 333 | [ |
||
| 334 | 'redirect' => &$redirect, |
||
| 335 | ], |
||
| 336 | ]; |
||
| 337 | $result = \call_user_func_array([$plugin, 'retourMatch'], $args); |
||
| 338 | if ($result) { |
||
| 339 | $this->incrementRedirectHitCount($redirect); |
||
| 340 | $this->saveRedirectToCache($url, $redirect); |
||
| 341 | |||
| 342 | return $redirect; |
||
| 343 | } |
||
| 344 | } |
||
| 345 | break; |
||
| 346 | } |
||
| 347 | } |
||
| 348 | } |
||
| 349 | Craft::info( |
||
| 350 | Craft::t( |
||
| 351 | 'retour', |
||
| 352 | 'Not handled-> full URL: {fullUrl}, path only: {pathOnly}', |
||
| 353 | ['fullUrl' => $fullUrl, 'pathOnly' => $pathOnly] |
||
| 354 | ), |
||
| 355 | __METHOD__ |
||
| 356 | ); |
||
| 357 | |||
| 358 | return $result; |
||
| 359 | } |
||
| 360 | |||
| 361 | /** |
||
| 362 | * Returns the list of matching schemes |
||
| 363 | * |
||
| 364 | * @return array |
||
| 365 | */ |
||
| 366 | public function getMatchesList(): array |
||
| 382 | } |
||
| 383 | |||
| 384 | /** |
||
| 385 | * @param null|int $limit |
||
| 386 | * |
||
| 387 | * @return array All of the statistics |
||
| 388 | */ |
||
| 389 | public function getAllStaticRedirects($limit = null): array |
||
| 390 | { |
||
| 391 | // Cache it in our class; no need to fetch it more than once |
||
| 392 | if ($this->cachedStaticRedirects !== null) { |
||
| 393 | return $this->cachedStaticRedirects; |
||
| 394 | } |
||
| 395 | // Query the db table |
||
| 396 | $query = (new Query()) |
||
| 397 | ->from(['{{%retour_static_redirects}}']) |
||
| 398 | ->orderBy('redirectMatchType ASC, redirectSrcMatch ASC, hitCount DESC'); |
||
| 399 | if ($limit) { |
||
|
|
|||
| 400 | $query->limit($limit); |
||
| 401 | } |
||
| 402 | $redirects = $query->all(); |
||
| 403 | // Cache for future accesses |
||
| 404 | $this->cachedStaticRedirects = $redirects; |
||
| 405 | |||
| 406 | return $redirects; |
||
| 407 | } |
||
| 408 | |||
| 409 | /** |
||
| 410 | * Return a redirect by id |
||
| 411 | * |
||
| 412 | * @param int $id |
||
| 413 | * |
||
| 414 | * @return null|array The static redirect |
||
| 415 | */ |
||
| 416 | public function getRedirectById(int $id) |
||
| 417 | { |
||
| 418 | // Query the db table |
||
| 419 | $redirect = (new Query()) |
||
| 420 | ->from(['{{%retour_static_redirects}}']) |
||
| 421 | ->where(['id' => $id]) |
||
| 422 | ->one(); |
||
| 423 | |||
| 424 | return $redirect; |
||
| 425 | } |
||
| 426 | |||
| 427 | /** |
||
| 428 | * Return a redirect by redirectSrcUrl |
||
| 429 | * |
||
| 430 | * @param string $redirectSrcUrl |
||
| 431 | * |
||
| 432 | * @return null|array |
||
| 433 | */ |
||
| 434 | public function getRedirectByRedirectSrcUrl(string $redirectSrcUrl) |
||
| 443 | } |
||
| 444 | |||
| 445 | /** |
||
| 446 | * Delete a redirect by id |
||
| 447 | * |
||
| 448 | * @param int $id |
||
| 449 | * |
||
| 450 | * @return int The result |
||
| 451 | */ |
||
| 452 | public function deleteRedirectById(int $id): int |
||
| 469 | } |
||
| 470 | |||
| 471 | /** |
||
| 472 | * Increment the retour_static_redirects record |
||
| 473 | * |
||
| 474 | * @param $redirectConfig |
||
| 475 | */ |
||
| 476 | public function incrementRedirectHitCount(&$redirectConfig) |
||
| 505 | } |
||
| 506 | } |
||
| 507 | } |
||
| 508 | |||
| 509 | /** |
||
| 510 | * @param array $redirectConfig |
||
| 511 | */ |
||
| 512 | public function saveRedirect(array $redirectConfig) |
||
| 607 | } |
||
| 608 | } |
||
| 609 | } |
||
| 610 | |||
| 611 | /** |
||
| 612 | * Invalidate all of the redirects caches |
||
| 613 | */ |
||
| 614 | public function invalidateCaches() |
||
| 627 |
In PHP, under loose comparison (like
==, or!=, orswitchconditions), values of different types might be equal.For
integervalues, zero is a special case, in particular the following results might be unexpected: