src/Service/LocaleSubscriber.php line 33

Open in your IDE?
  1. <?php
  2. /*
  3. * To change this license header, choose License Headers in Project Properties.
  4. * To change this template file, choose Tools | Templates
  5. * and open the template in the editor.
  6. */
  7. namespace App\Service;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpKernel\Event\RequestEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. class LocaleSubscriber implements EventSubscriberInterface
  12. {
  13. private $defaultLocale;
  14. public function __construct($defaultLocale = 'en')
  15. {
  16. $this->defaultLocale = $defaultLocale;
  17. }
  18. public function onKernelRequest(RequestEvent $event)
  19. {
  20. $request = $event->getRequest();
  21. if (!$request->hasPreviousSession()) {
  22. return;
  23. }
  24. // try to see if the locale has been set as a _locale routing parameter
  25. if ($locale = $request->attributes->get('_locale')) {
  26. $request->getSession()->set('_locale', $locale);
  27. } else {
  28. // if no explicit locale has been set on this request, use one from the session
  29. $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
  30. }
  31. }
  32. public static function getSubscribedEvents()
  33. {
  34. return [
  35. // must be registered before (i.e. with a higher priority than) the default Locale listener
  36. KernelEvents::REQUEST => [['onKernelRequest', 20]],
  37. ];
  38. }
  39. }