src/EventSubscriber/LocaleSubscriber.php line 34

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. class LocaleSubscriber implements EventSubscriberInterface
  7. {
  8. // Langue par défaut
  9. private $defaultLocale = 'fr';
  10. public function __construct()
  11. {
  12. }
  13. public function onKernelRequest(\Symfony\Component\HttpKernel\Event\RequestEvent $event)
  14. {
  15. $request = $event->getRequest();
  16. // if (!$event->isMainRequest()) {
  17. // // don't do anything if it's not the main request
  18. // return;
  19. // }
  20. if (!$request->hasPreviousSession()) {
  21. return;
  22. }
  23. if ($locale = $request->query->get('language')) {
  24. $request->setLocale($locale);
  25. $request->getSession()->set('language',$locale);
  26. } else {
  27. $request->setLocale($request->getSession()->get('language', $this->defaultLocale));
  28. }
  29. }
  30. public static function getSubscribedEvents()
  31. {
  32. return [
  33. // On doit définir une priorité élevée
  34. KernelEvents::REQUEST => [['onKernelRequest', 20]],
  35. ];
  36. }
  37. }