Skip to content

Commit 1fa7729

Browse files
authored
fix(Router): handle {locale} placeholder in redirect routes (#10761)
* fix(Router): handle {locale} placeholder in redirect routes * test(Router): cover redirect status code and locale edge cases * test(Router): test non-default redirect status code and clean up comment * docs: add changelog entry for redirect route {locale} fix
1 parent 55ca87b commit 1fa7729

3 files changed

Lines changed: 48 additions & 17 deletions

File tree

‎docs/changelogs/v4.7.7.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ Release Date: Unreleased
2929
- **HTTP:** Fixed a bug where query-string based routing truncated additional query parameters in `SiteURIFactory::parseRequestURI()` due to incorrect array index access.
3030
- **HTTP:** Fixed a bug where `UploadedFile::move()` and `UploadedFile::store()` on Windows could store a file under a different name than `getName()` reported, or write its contents to an NTFS alternate data stream. Filenames ending in a period or space or containing a colon are now rejected, including explicitly supplied names.
3131
- **Images:** Fixed a bug in `ImageMagickHandler::save()` where saving without an extension or with an unsupported extension threw an `ImagickException` instead of falling back to the image's format.
32+
- **Routing:** Fixed a bug where redirect routes containing the `{locale}` placeholder were not recognized as redirects and did not replace `{locale}` in the redirect target.
3233
- **Security:** Fixed a bug where `Security::__construct()` threw a `TypeError` when the CSRF cookie was an array, causing an HTTP 500 response for affected requests.
3334
- **Security:** Fixed a bug in `strip_image_tags()` where an invalid PCRE character class caused attribute injection and improper quote handling, and ensured tags without `src` are stripped.
3435
- **Session:** Fixed a bug where `BaseHandler::destroyCookie()` did not send the `SameSite` attribute in the `Set-Cookie` header, which could prevent browsers from properly clearing the session cookie.

‎system/Router/Router.php‎

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -457,20 +457,6 @@ protected function checkRoutes(string $uri): bool
457457

458458
// Does the RegEx match?
459459
if (preg_match('#^' . $routeKey . '$#u', $uri, $matches)) {
460-
// Is this route supposed to redirect to another?
461-
if ($this->collection->isRedirect($routeKey)) {
462-
// replacing matched route groups with references: post/([0-9]+) -> post/$1
463-
$redirectTo = preg_replace_callback('/(\([^\(]+\))/', static function (): string {
464-
static $i = 1;
465-
466-
return '$' . $i++;
467-
}, is_array($handler) ? key($handler) : $handler);
468-
469-
throw new RedirectException(
470-
preg_replace('#\A' . $routeKey . '\z#u', $redirectTo, $uri),
471-
$this->collection->getRedirectCode($routeKey),
472-
);
473-
}
474460
// Store our locale so CodeIgniter object can
475461
// assign it to the Request.
476462
if (str_contains($matchedKey, '{locale}')) {
@@ -491,6 +477,24 @@ protected function checkRoutes(string $uri): bool
491477
unset($matched);
492478
}
493479

480+
if ($this->collection->isRedirect($matchedKey)) {
481+
// replacing matched route groups with references: post/([0-9]+) -> post/$1
482+
$redirectTo = preg_replace_callback('/(\([^\(]+\))/', static function (): string {
483+
static $i = 1;
484+
485+
return '$' . $i++;
486+
}, is_array($handler) ? key($handler) : $handler);
487+
488+
if (str_contains($matchedKey, '{locale}')) {
489+
$redirectTo = str_replace('{locale}', $this->detectedLocale, $redirectTo);
490+
}
491+
492+
throw new RedirectException(
493+
preg_replace('#\A' . $routeKey . '\z#u', $redirectTo, $uri),
494+
$this->collection->getRedirectCode($matchedKey),
495+
);
496+
}
497+
494498
// Are we using Closures? If so, then we need
495499
// to collect the params into an array
496500
// so it can be passed to the controller method later.

‎tests/system/Router/RouterTest.php‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -949,36 +949,62 @@ public function testRedirectRoute(
949949
string $url,
950950
string $expectedPath,
951951
string $alias,
952+
int $status = 302,
952953
): void {
953954
$collection = clone $this->collection;
954955
$collection->resetRoutes();
955956

956957
$collection->get($route, 'Controller::method', ['as' => $alias]);
957-
$collection->addRedirect($redirectFrom, $redirectTo);
958+
$collection->addRedirect($redirectFrom, $redirectTo, $status);
958959

959960
$this->expectException(RedirectException::class);
960961
$this->expectExceptionMessage($expectedPath);
962+
$this->expectExceptionCode($status);
961963

962964
$router = new Router($collection, $this->request);
963965
$router->handle($url);
964966
}
965967

966968
/**
967-
* @return iterable<int, array{string, string, string, string, string, string}>
969+
* @return iterable<int, array{string, string, string, string, string, string, 6?: int}>
968970
*/
969971
public static function provideRedirectRoute(): iterable
970972
{
971-
// [$route, $redirectFrom, $redirectTo, $url, $expectedPath, $alias]
973+
// [$route, $redirectFrom, $redirectTo, $url, $expectedPath, $alias, $status]
972974
return [
973975
['posts', 'articles', 'posts', '/articles', 'posts', 'alias'],
974976
['posts', 'articles', 'alias', '/articles', 'posts', 'alias'],
975977
['post/(:num)', 'article/(:num)', 'post/$1', '/article/1', 'post/1', 'alias'],
976978
['post/(:num)', 'article/(:num)', 'alias', '/article/1', 'post/1', 'alias'],
977979
['post/(:num)/comment/(:any)', 'article/(:num)/(:any)', 'post/$1/comment/$2', '/article/1/2', 'post/1/comment/2', 'alias'],
978980
['post/(:segment)/comment/(:any)', 'article/(:num)/(:any)', 'alias', '/article/1/2', 'post/1/comment/2', 'alias'],
981+
['posts', '{locale}/articles', 'posts', '/en/articles', 'posts', 'alias'],
982+
['{locale}/posts', '{locale}/articles', '{locale}/posts', '/en/articles', 'en/posts', 'alias'],
983+
['{locale}/posts', '{locale}/articles', '{locale}/posts', '/en/articles', 'en/posts', 'alias', 301],
984+
['{locale}/posts', '{locale}/articles', 'alias', '/en/articles', 'en/posts', 'alias'],
985+
['{locale}/post/(:num)', '{locale}/article/(:num)', '{locale}/post/$1', '/en/article/1', 'en/post/1', 'alias'],
986+
['{locale}/post/(:num)', '{locale}/article/(:num)', 'alias', '/en/article/1', 'en/post/1', 'alias'],
979987
];
980988
}
981989

990+
public function testRedirectRouteWithUnsupportedLocale(): void
991+
{
992+
$config = config(App::class);
993+
$config->supportedLocales = ['en'];
994+
995+
$collection = clone $this->collection;
996+
$collection->resetRoutes();
997+
$collection->useSupportedLocalesOnly(true);
998+
999+
$collection->get('{locale}/posts', 'Controller::method');
1000+
$collection->addRedirect('{locale}/articles', '{locale}/posts');
1001+
1002+
$this->expectException(PageNotFoundException::class);
1003+
1004+
$router = new Router($collection, $this->request);
1005+
$router->handle('/fr/articles');
1006+
}
1007+
9821008
public function testRoutePlaceholderAnyWithMultipleSegmentsParamFalse(): void
9831009
{
9841010
$this->createRouteCollection();

0 commit comments

Comments
 (0)