src/EventSubscriber/LocaleSetter.php line 41

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\Cookie;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. class LocaleSetter  implements EventSubscriberInterface
  9. {
  10.     private const COOKIES_LOCALE_KEY '_lang';
  11.     private const AVAILABLE_LOCALES = ['en','ru','ua'];
  12.     public static function getSubscribedEvents(): array
  13.     {
  14.         // return the subscribed events, their methods and priorities
  15.         return [
  16.             KernelEvents::REQUEST => [
  17.                 ['onKernelRequest'20],
  18.             ],
  19.             KernelEvents::RESPONSE => [
  20.                 ['onKernelResponse'20],
  21.             ]
  22.         ];
  23.     }
  24.     private $defaultLocale;
  25.     public function __construct(string $defaultLocale 'en')
  26.     {
  27.         $this->defaultLocale $defaultLocale;
  28.     }
  29.     public function onKernelRequest(RequestEvent $event)
  30.     {
  31.         $request $event->getRequest();
  32.         $browser_pref $request->getPreferredLanguage(self::AVAILABLE_LOCALES);
  33.         $this->defaultLocale $request->cookies->get(self::COOKIES_LOCALE_KEY,$browser_pref);
  34.         $request_locale $request->getSession()->get(self::COOKIES_LOCALE_KEY$this->defaultLocale);
  35.         if ($locale $request->attributes->get('_locale')) {
  36.             $request_locale $locale;
  37.         }
  38.         if (!in_array($request_locale self::AVAILABLE_LOCALES)){
  39.             $request_locale self::AVAILABLE_LOCALES[0];
  40.         }
  41.         $request->getSession()->set(self::COOKIES_LOCALE_KEY,$request_locale);
  42.         $request->setLocale($request_locale);
  43.     }
  44.     public function onKernelResponse(ResponseEvent $event){
  45.         $request $event->getRequest();
  46.         $response $event->getResponse();
  47.         $current_locale $request->getLocale();
  48.         $current_cookie $request->cookies->get(self::COOKIES_LOCALE_KEY'');
  49.         if ($current_cookie !== $current_locale){
  50.             $response->headers->setCookie(new Cookie(self::COOKIES_LOCALE_KEY$current_locale));
  51.         }
  52.     }
  53. }