すべてのルートまたはグローバル スコープに要件を設定するよりも優れた解決策は、EventListener を使用してユーザーを同じルートにリダイレクトすることですが、サポートされているロケールを使用します。例:
<?php
namespace Selly\WebappLandingBundle\EventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LocaleInParamListener implements EventSubscriberInterface
{
/**
* @var Symfony\Component\Routing\RouterInterface
*/
private $router;
/**
* @var string
*/
private $defaultLocale;
/**
* @var array
*/
private $supportedLocales;
/**
* @var string
*/
private $localeRouteParam;
public function __construct(RouterInterface $router, $defaultLocale = 'en_US', array $supportedLocales = array('en_US'), $localeRouteParam = '_locale')
{
$this->router = $router;
$this->defaultLocale = $defaultLocale;
$this->supportedLocales = $supportedLocales;
$this->localeRouteParam = $localeRouteParam;
}
public function isLocaleSupported($locale) {
return in_array($locale, $this->supportedLocales);
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$locale = $request->get($this->localeRouteParam);
if(null !== $locale) {
$routeName = $request->get('_route');
if(!$this->isLocaleSupported($locale)) {
$routeParams = $request->get('_route_params');
if (!$this->isLocaleSupported($this->defaultLocale))
throw \Exception("Default locale is not supported.");
$routeParams[$this->localeRouteParam] = $this->defaultLocale;
$url = $this->router->generate($routeName, $routeParams);
$event->setResponse(new RedirectResponse($url));
}
}
}
public static function getSubscribedEvents()
{
return array(
// must be registered before the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
);
}
}
とservices.yml
services:
selly_webapp_landing.listeners.localeInParam_listener:
class: Selly\WebappLandingBundle\EventListener\LocaleInParamListener
arguments: [@router, "%kernel.default_locale%", "%locale_supported%"]
tags:
- { name: kernel.event_subscriber }
parameters.yml
サポートされているロケールを指定できます。
locale_supported: ['en_US', 'pl_PL']