Skip to content

Commit

Permalink
Merge pull request #1 from f-E-T/main
Browse files Browse the repository at this point in the history
Allow language to be the only path part in URI
  • Loading branch information
fabiang authored Feb 2, 2024
2 parents 5dfbb12 + 17645c7 commit 1c928b4
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/Mvc/Router/Http/LanguageTreeRouteStack.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,16 @@ public function match(RequestInterface $request, $pathOffset = null, array $opti
if (count($languages) > 1 && in_array($pathParts[0], $languageKeys)) {
// if language was provided, save the locale and adjust the baseUrl
$locale = $languages[$pathParts[0]];
$this->setBaseUrl($oldBase . '/' . $pathParts[0]);

// if only the language was provided
if (count($pathParts) === 1) {
$this->baseUrl = '';
$uri->setPath('/');
$pathOffset = 0;
// if the language was provided along with other path parts
} else {
$this->setBaseUrl($oldBase . '/' . $pathParts[0]);
}
} elseif (! empty($this->getAuthenticationService()) && $this->getAuthenticationService()->hasIdentity()) {
// try to get user language if no language was provided by url
$user = $this->getAuthenticationService()->getIdentity();
Expand Down
28 changes: 28 additions & 0 deletions tests/src/Mvc/Router/Http/LanguageTreeRouteStackMatchTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,34 @@ public function matchLocaleFromURI(): void
$this->assertSame('de_DE', $this->route->getLastMatchedLocale());
}

/**
* @test
* @covers ::match
* @covers ::getLastMatchedLocale
*/
public function matchLocaleFromURIWithoutPath(): void
{
$translator = $this->prophesize(Translator::class);
$translator->getLocale()->willReturn('de_DE');

$options = new LanguageRouteOptions();
$this->route->setLanguageOptions($options);

$this->route->setBaseUrl('/');
$this->route->addRoute('phpunit', ['type' => 'literal', 'options' => ['route' => '/']]);

$uri = new URI('http://phpunit/de');
$request = $this->prophesize(Request::class);
$request->getUri()->willReturn($uri);

$routeMatch = $this->route->match($request->reveal(), null, ['translator' => $translator->reveal()]);
$this->assertInstanceOf(RouteMatch::class, $routeMatch);
$this->assertSame('phpunit', $routeMatch->getMatchedRouteName());
$this->assertSame(['locale' => 'de_DE'], $routeMatch->getParams());
$this->assertSame('', $this->route->getBaseUrl());
$this->assertSame('de_DE', $this->route->getLastMatchedLocale());
}

/**
* @test
* @covers ::match
Expand Down

0 comments on commit 1c928b4

Please sign in to comment.