src/EventSubscriber/LanguageListener.php line 36

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  4. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. use Symfony\Component\HttpKernel\KernelInterface;
  8. use Symfony\Component\HttpKernel\Event\RequestEvent;
  9. use Negotiation\LanguageNegotiator;
  10. use Symfony\Component\HttpFoundation\RedirectResponse;
  11. class LanguageListener implements EventSubscriberInterface
  12. {
  13.     private $supportedLanguages;
  14.     public function __construct(string $supportedLanguages)
  15.     {
  16.         $supportedLanguages explode('|'$supportedLanguages);
  17.         if (empty($supportedLanguages)) {
  18.             throw new \InvalidArgumentException('At least one supported language must be given.');
  19.         }
  20.         $this->supportedLanguages $supportedLanguages;
  21.     }
  22.     public static function getSubscribedEvents()
  23.     {
  24.         return [
  25.             KernelEvents::REQUEST  => ['redirectToLocalizedHomepage'100],
  26.         ];
  27.     }
  28.     public function redirectToLocalizedHomepage(RequestEvent $event)
  29.     {
  30.         // Do not modify sub-requests
  31.         if (KernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
  32.             return;
  33.         }
  34.         // Assume all routes except the frontpage use the _locale parameter
  35.         if ($event->getRequest()->getPathInfo() !== '/') {
  36.             return;
  37.         }
  38.         $language $this->supportedLanguages[0];
  39.         if (null !== $acceptLanguage $event->getRequest()->headers->get('Accept-Language')) {
  40.             $negotiator = new LanguageNegotiator();
  41.             $best       $negotiator->getBest(
  42.                 $event->getRequest()->headers->get('Accept-Language'),
  43.                 $this->supportedLanguages
  44.             );
  45.             if (null !== $best) {
  46.                 $language $best->getType();
  47.             }
  48.         }
  49.         $response = new RedirectResponse('/' $language);
  50.         $event->setResponse($response);
  51.     }
  52. }