Skip to content

Commit

Permalink
Merge pull request #6003 from iRedds/fix/detect-locale-placeholder
Browse files Browse the repository at this point in the history
Fix: Route placeholder (:any) with {locale}
  • Loading branch information
samsonasik committed May 19, 2022
2 parents caf0376 + 8e71cd6 commit 8a8c183
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
23 changes: 10 additions & 13 deletions system/Router/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -403,9 +403,6 @@ protected function checkRoutes(string $uri): bool

// Loop through the route array looking for wildcards
foreach ($routes as $routeKey => $handler) {
// Reset localeSegment
$localeSegment = null;

$routeKey = $routeKey === '/'
? $routeKey
: ltrim($routeKey, '/ ');
Expand All @@ -414,12 +411,7 @@ protected function checkRoutes(string $uri): bool

// Are we dealing with a locale?
if (strpos($routeKey, '{locale}') !== false) {
$localeSegment = array_search('{locale}', preg_split('/[\/]*((^[a-zA-Z0-9])|\(([^()]*)\))*[\/]+/m', $routeKey), true);

// Replace it with a regex so it
// will actually match.
$routeKey = str_replace('/', '\/', $routeKey);
$routeKey = str_replace('{locale}', '[^\/]+', $routeKey);
$routeKey = str_replace('{locale}', '[^/]+', $routeKey);
}

// Does the RegEx match?
Expand All @@ -440,10 +432,15 @@ protected function checkRoutes(string $uri): bool
}
// Store our locale so CodeIgniter object can
// assign it to the Request.
if (isset($localeSegment)) {
// The following may be inefficient, but doesn't upset NetBeans :-/
$temp = (explode('/', $uri));
$this->detectedLocale = $temp[$localeSegment];
if (strpos($matchedKey, '{locale}') !== false) {
preg_match(
'#^' . str_replace('{locale}', '(?<locale>[^/]+)', $matchedKey) . '$#u',
$uri,
$matched
);

$this->detectedLocale = $matched['locale'];
unset($matched);
}

// Are we using Closures? If so, then we need
Expand Down
6 changes: 6 additions & 0 deletions tests/system/Router/RouterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ protected function setUp(): void
'books/(:num)/(:alpha)/(:num)' => 'Blog::show/$3/$1',
'closure/(:num)/(:alpha)' => static fn ($num, $str) => $num . '-' . $str,
'{locale}/pages' => 'App\Pages::list_all',
'test/(:any)/lang/{locale}' => 'App\Pages::list_all',
'admin/admins' => 'App\Admin\Admins::list_all',
'admin/admins/edit/(:any)' => 'App/Admin/Admins::edit_show/$1',
'/some/slash' => 'App\Slash::index',
Expand Down Expand Up @@ -402,6 +403,11 @@ public function testDetectsLocales()

$this->assertTrue($router->hasLocale());
$this->assertSame('fr', $router->getLocale());

$router->handle('test/123/lang/bg');

$this->assertTrue($router->hasLocale());
$this->assertSame('bg', $router->getLocale());
}

public function testRouteResource()
Expand Down

0 comments on commit 8a8c183

Please sign in to comment.