src/EventSubscriber/LocaleSubscriber.php line 22

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. use w3des\AdminBundle\Service\CMS;
  7. class LocaleSubscriber implements EventSubscriberInterface
  8. {
  9. private $defaultLocale;
  10. private $pageLocales;
  11. public function __construct(string $defaultLocale, array $pageLocales)
  12. {
  13. $this->defaultLocale = $defaultLocale;
  14. $this->pageLocales = $pageLocales;
  15. }
  16. public function onKernelRequest(RequestEvent $event)
  17. {
  18. $request = $event->getRequest();
  19. if ($event->isMainRequest()) {
  20. $locale = $request->cookies->get('LOCALE');
  21. if (!\in_array($locale, $this->pageLocales)) {
  22. $locale = null;
  23. }
  24. if ($locale) {
  25. $request->setLocale($locale);
  26. } else {
  27. $request->setLocale($this->defaultLocale);
  28. }
  29. }
  30. }
  31. public static function getSubscribedEvents()
  32. {
  33. return [
  34. // must be registered before (i.e. with a higher priority than) the default Locale listener
  35. KernelEvents::REQUEST => [
  36. [
  37. 'onKernelRequest',
  38. 20
  39. ]
  40. ]
  41. ];
  42. }
  43. }