src/EventSubscriber/SetLanguageCookieSubscriber.php line 13

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\Cookie;
  6. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. class SetLanguageCookieSubscriber implements EventSubscriberInterface
  9. {
  10.     public function onKernelResponse(ResponseEvent $event)
  11.     {
  12.         $request $event->getRequest();
  13.         if (!$event->isMasterRequest()) {
  14.             return;
  15.         }
  16.         if ($request->attributes->get('_route') == '_wdt') {
  17.             return;
  18.         }
  19.         if ($request->getPathInfo() && strpos($request->getPathInfo(), '_wdt') !== false) {
  20.             return;
  21.         }
  22.         $newUrl  strtolower($request->getPathInfo());
  23.         if (preg_match_all("/js\/routing/"$newUrl) || preg_match_all("/[a-z]{2}\/notifications\/widget/"$newUrl)
  24.             || $newUrl === '/' || preg_match_all("#/_fragment#"$newUrl)) {
  25.             return;
  26.         }
  27.         $response $event->getResponse();
  28.         $locale $event->getRequest()->getLocale();
  29.         $response->headers->setCookie(new Cookie('preferred_language'$locale));
  30.     }
  31.     /**
  32.      * @return array
  33.      */
  34.     public static function getSubscribedEvents()
  35.     {
  36.         return [
  37.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  38.             KernelEvents::RESPONSE => [['onKernelResponse', -1050]],
  39.         ];
  40.     }
  41. }