Files
vindn.de/frontend/src/Controller/LanguageController.php
T
2026-10-09 16:37:53 +02:00

42 lines
1.6 KiB
PHP

<?php
namespace App\Controller;
use App\EventSubscriber\LocaleSubscriber;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
class LanguageController extends AbstractController
{
/** @param list<string> $enabledLocales */
public function __construct(
#[Autowire('%kernel.enabled_locales%')]
private readonly array $enabledLocales,
) {
}
/** Remembers the chosen language in a cookie and returns to the page it was chosen on. */
#[Route('/language/{locale}', name: 'language_switch', requirements: ['locale' => '[a-z]{2}'])]
public function switch(string $locale, Request $request): RedirectResponse
{
if (!\in_array($locale, $this->enabledLocales, true)) {
throw $this->createNotFoundException();
}
// Only ever back to a path on this site — never an open redirect.
$back = (string) $request->query->get('back', '/');
if (!str_starts_with($back, '/') || str_starts_with($back, '//') || str_contains($back, '\\')) {
$back = '/';
}
$response = $this->redirect($back);
$response->headers->setCookie(Cookie::create(LocaleSubscriber::COOKIE, $locale, strtotime('+1 year'), '/', null, $request->isSecure(), false, false, Cookie::SAMESITE_LAX));
return $response;
}
}