Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 0 additions & 12 deletions phpstan-baseline.php
Original file line number Diff line number Diff line change
Expand Up @@ -1405,12 +1405,6 @@
'count' => 1,
'path' => __DIR__ . '/src/Controller/Frontend/ListingController.php',
];
$ignoreErrors[] = [
'message' => '#^Method Bolt\\\\Controller\\\\Frontend\\\\ListingController\\:\\:listing\\(\\) should return Symfony\\\\Component\\\\HttpFoundation\\\\Response but returns Symfony\\\\Component\\\\HttpFoundation\\\\Response\\|null\\.$#',
'identifier' => 'return.type',
'count' => 1,
'path' => __DIR__ . '/src/Controller/Frontend/ListingController.php',
];
$ignoreErrors[] = [
'message' => '#^Method Bolt\\\\Controller\\\\Frontend\\\\ListingController\\:\\:parseQueryParams\\(\\) return type has no value type specified in iterable type array\\.$#',
'identifier' => 'missingType.iterableValue',
Expand Down Expand Up @@ -1495,12 +1489,6 @@
'count' => 1,
'path' => __DIR__ . '/src/Controller/TwigAwareController.php',
];
$ignoreErrors[] = [
'message' => '#^Method Bolt\\\\Controller\\\\TwigAwareController\\:\\:renderSingle\\(\\) should return Symfony\\\\Component\\\\HttpFoundation\\\\Response but returns Symfony\\\\Component\\\\HttpFoundation\\\\Response\\|null\\.$#',
'identifier' => 'return.type',
'count' => 1,
'path' => __DIR__ . '/src/Controller/TwigAwareController.php',
];
$ignoreErrors[] = [
'message' => '#^Method Bolt\\\\Controller\\\\TwigAwareController\\:\\:renderTemplate\\(\\) has parameter \\$parameters with no value type specified in iterable type array\\.$#',
'identifier' => 'missingType.iterableValue',
Expand Down
47 changes: 46 additions & 1 deletion src/Controller/ErrorController.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Translation\LocaleSwitcher;
use Throwable;
use Twig\Environment;
use Twig\Error\LoaderError;
Expand All @@ -37,10 +38,17 @@ public function __construct(
private readonly UrlGeneratorInterface $urlGenerator,
private readonly Security $security,
private readonly RequestStack $requestStack,
private readonly LocaleSwitcher $localeSwitcher,
string $locales,
) {
parent::__construct($httpKernel, $this->templateController, $errorRenderer);

$this->localeCodes = explode('|', $locales);
}

/** @var list<string> */
private readonly array $localeCodes;

/**
* Show an exception. Mainly used for custom 404 pages, otherwise falls back
* to Symfony's error handling
Expand All @@ -61,6 +69,8 @@ public function showAction(Environment $twig, Throwable $exception): Response

// We need the parent request here, but fall back to current if not found
if ($request = $this->requestStack->getParentRequest() ?? $this->requestStack->getCurrentRequest()) {
$this->setLocaleFromPath($request);

if ($code === Response::HTTP_SERVICE_UNAVAILABLE || $this->isMaintenanceEnabled($code)) {
$twig->addGlobal('exception', $exception);

Expand Down Expand Up @@ -156,6 +166,40 @@ private function isMaintenanceEnabled(int $code): bool
return filter_var($this->config->get('general/maintenance_mode', false), FILTER_VALIDATE_BOOLEAN);
}

/**
* Recovers the locale from the first path segment (e.g. `/de/...` => `de`),
* which Symfony's `LocaleListener` never did because no route matched.
*
* Applied to the given request and to the current one (a sub-request when an
* error page is rendered, which Twig's `app.request` resolves to). The
* `LocaleSwitcher` then syncs the translator and the router's `RequestContext`,
* so `{% trans %}` strings and `path()` calls follow suit.
*/
private function setLocaleFromPath(Request $request): void
{
// Only derive the locale from the path when routing didn't run. With a
// matched route the locale is already set, and the first segment is a
// ContentType slug rather than a locale: a ContentType `it` isn't Italian.
if (! $request->attributes->has('_route')) {
// Cast: `mb_trim()` is analysed as `string|false`, but `getPathInfo()`
// always returns a string.
$segment = explode('/', (string) mb_trim($request->getPathInfo(), '/'))[0];

if ($segment !== '' && in_array($segment, $this->localeCodes, true)) {
$request->setLocale($segment);
}
}

// The error sub-request is a fresh Request that never saw the URL's locale,
// so propagate it regardless of how the locale was determined.
$currentRequest = $this->requestStack->getCurrentRequest();
if ($currentRequest instanceof Request && $currentRequest !== $request) {
$currentRequest->setLocale($request->getLocale());
}

$this->localeSwitcher->setLocale($request->getLocale());
}
Comment thread
Vondry marked this conversation as resolved.

private function attemptToRender(Request $request, string $item): ?Response
{
// First, see if it's a contenttype/slug pair:
Expand All @@ -165,7 +209,8 @@ private function attemptToRender(Request $request, string $item): ?Response
// We wrap it in a try/catch, because we wouldn't want to
// trigger a 404 within a 404 now, would we?
try {
return $this->detailController->record($request, $slug, $contentType, false, null);
// Pass the locale explicitly, or the record falls back to the default.
return $this->detailController->record($request, $slug, $contentType, false, $request->getLocale());
} catch (NotFoundHttpException) {
// Just continue to the next one.
}
Expand Down
5 changes: 3 additions & 2 deletions src/Controller/Frontend/ListingController.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,9 @@ public function listing(Request $request, ContentRepository $contentRepository,
}

// If the locale is the wrong locale
if (! $this->validLocaleForContentType($request, $contentType)) {
return $this->redirectToDefaultLocale($request);
if (! $this->validLocaleForContentType($request, $contentType)
&& ($redirect = $this->redirectToDefaultLocaleOrFallback($request)) instanceof Response) {
return $redirect;
}

$page = (int) $this->getFromRequest($request, 'page', '1');
Expand Down
36 changes: 33 additions & 3 deletions src/Controller/TwigAwareController.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,9 @@ public function renderSingle(Request $request, ?Content $record, bool $requirePu
}

// If the locale is the wrong locale
if (! $this->validLocaleForContentType($request, $recordDefinition)) {
return $this->redirectToDefaultLocale($request);
if (! $this->validLocaleForContentType($request, $recordDefinition)
&& ($redirect = $this->redirectToDefaultLocaleOrFallback($request)) instanceof Response) {
return $redirect;
}

$singularSlug = $record->getContentTypeSingularSlug();
Expand Down Expand Up @@ -145,8 +146,37 @@ protected function validLocaleForContentType(Request $request, ContentType $cont
return $request->getLocale() === $this->defaultLocale;
}

/**
* Redirects to the same route in the default locale. When there's no route to
* redirect to (a forwarded request, or an error page where routing never
* matched), resets the request to the default locale and returns `null` so the
* caller can render instead of erroring.
*
* Only the given request is reset, so on an error page `<html lang>` may still
* show the URL locale while the record renders in the default one. Harmless:
* only non-localized content takes this path.
*/
protected function redirectToDefaultLocaleOrFallback(Request $request): ?Response
{
$redirect = $this->redirectToDefaultLocale($request);

if ($redirect instanceof Response) {
return $redirect;
}

$request->setLocale($this->defaultLocale);

return null;
}

protected function redirectToDefaultLocale(Request $request): ?Response
{
// No route matched (e.g. on an error page): nothing to redirect to.
$route = $request->attributes->get('_route');
if (! $route) {
return null;
}

$request->getSession()->set('_locale', $this->defaultLocale);

$params = $request->attributes->get('_route_params');
Expand All @@ -155,7 +185,7 @@ protected function redirectToDefaultLocale(Request $request): ?Response
$params['_locale'] = $this->defaultLocale;
}

return $this->redirectToRoute($request->get('_route'), $params);
return $this->redirectToRoute($route, $params);
}

private function setTwigLoader(): void
Expand Down
Loading
Loading