Skip to content

Commit

Permalink
Redirect language URLs with non-translated slugs
Browse files Browse the repository at this point in the history
Fixes #3550
  • Loading branch information
distantnative committed Aug 11, 2024
1 parent 4fd365c commit 8e8f9e5
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 2 deletions.
20 changes: 19 additions & 1 deletion src/Cms/LanguageRoutes.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Kirby\Cms;

use Kirby\Filesystem\F;
use Kirby\Toolkit\Str;

class LanguageRoutes
{
Expand All @@ -29,9 +30,26 @@ public static function create(App $kirby): array
'pattern' => $language->pattern(),
'method' => 'ALL',
'env' => 'site',
'action' => function ($path = null) use ($language) {
'action' => function ($path = null) use ($kirby, $language) {
$result = $language->router()->call($path);

// redirect secondary-language pages that have
// been accessed with non-translated slugs in their path
// to their fully translated URL
if ($path !== null && $result instanceof Page) {
if (Str::endsWith($result->url(), $path) === false) {
$url = $result->url();
$query = $kirby->request()->query()->toString();

// preserve query across redirect
if (empty($query) === false) {
$url .= '?' . $query;
}

return Response::redirect($url);
}
}

// explicitly test for null as $result can
// contain falsy values that should still be returned
if ($result !== null) {
Expand Down
38 changes: 38 additions & 0 deletions tests/Cms/Languages/LanguageRoutesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,42 @@ public function testNotNextWhenFalsyReturn()
$this->assertSame(1, $d);
$this->assertSame(2, $e);
}

public function testRedirectWhenNonTranslatedSlugs()
{
$app = $this->app->clone([
'site' => [
'children' => [
[
'slug' => 'page1',
'translations' => [
[
'code' => 'en',
],
[
'code' => 'de',
'slug' => 'seite1',
]
]
]
]
],
'request' => [
'query' => [
'foo' => 'bar',
]
]
]);

$result = $app->call('page1');
$this->assertSame($app->page('page1'), $result);

$result = $app->call('de/page1');
$this->assertInstanceOf(Response::class, $result);
$this->assertSame(302, $result->code());
$this->assertSame('/de/seite1?foo=bar', $result->header('Location'));

$result = $app->call('de/seite1');
$this->assertSame($app->page('page1'), $result);
}
}
1 change: 0 additions & 1 deletion tests/Uuid/PageUuidTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,6 @@ public function testMultilang(string $language, string $title)
],
[
'code' => 'de',
'slug' => 'bar',
'content' => [
'title' => 'Bar',
]
Expand Down

0 comments on commit 8e8f9e5

Please sign in to comment.