Skip to content

Commit

Permalink
Merge pull request #143 from cebe/patch-1
Browse files Browse the repository at this point in the history
Fix Url Matching for similar patterns
  • Loading branch information
mikehaertl authored Jun 18, 2018
2 parents 6f0c49e + 329bb26 commit f681040
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,8 @@ install:
- travis_retry composer clear-cache
- export PATH="$HOME/.composer/vendor/bin:$PATH"
- travis_retry composer install --prefer-dist --no-interaction --no-progress
- travis_retry composer require --dev phpunit/phpunit:^6.0 --prefer-dist --no-interaction --no-progress

script:
- php -doutput_buffering=On vendor/bin/phpunit

3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,7 @@ language code are no longer accessible:
### Language Configuration

All languages **including the default language** must be configured in the `languages`
parameter of the `localeUrls` component. You should list more specific language
codes before the similar looking generic ones (i.e. 'en-US' before 'en'):
parameter of the `localeUrls` component:

'languages' => ['en-US', 'en-UK', 'en', 'fr', 'de-AT', 'de'],

Expand Down
9 changes: 9 additions & 0 deletions UrlManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,15 @@ protected function processLocaleUrl($normalized)
$parts[] = $value;
}
}
// order by length to make longer patterns match before short patterns, e.g. put "en-GB" before "en"
usort($parts, function($a, $b) {
$la = mb_strlen($a);
$lb = mb_strlen($b);
if ($la === $lb) {
return 0;
}
return $la < $lb ? 1 : -1;
});
$pattern = implode('|', $parts);
if (preg_match("#^($pattern)\b(/?)#i", $pathInfo, $m)) {
$this->_request->setPathInfo(mb_substr($pathInfo, mb_strlen($m[1].$m[2])));
Expand Down
15 changes: 15 additions & 0 deletions tests/UrlManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,21 @@ public function testSetsLanguageFromUrl()
$this->assertEquals('site/page', $request->pathInfo);
}

public function testSetsLanguageFromUrlOrder()
{
$this->mockUrlManager([
'languages' => ['en', 'en-US', 'de'],
]);
$this->mockRequest('/en-us/site/page');
$this->assertEquals('en-US', Yii::$app->language);
$this->assertEquals('en-US', Yii::$app->session->get('_language'));
$cookie = Yii::$app->response->cookies->get('_language');
$this->assertNotNull($cookie);
$this->assertEquals('en-US', $cookie->value);
$request = Yii::$app->request;
$this->assertEquals('site/page', $request->pathInfo);
}

public function testSetsLanguageFromUrlIfUppercaseEnabled()
{
$this->mockUrlManager([
Expand Down

0 comments on commit f681040

Please sign in to comment.