vendor/sonata-project/translation-bundle/src/EventSubscriber/LocaleSubscriber.php line 39

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of the Sonata Project package.
  5. *
  6. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Sonata\TranslationBundle\EventSubscriber;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpKernel\Event\RequestEvent;
  14. use Symfony\Component\HttpKernel\KernelEvents;
  15. /**
  16. * @author Jonathan Vautrin <jvautrin@pro-info.be>
  17. */
  18. final class LocaleSubscriber implements EventSubscriberInterface
  19. {
  20. public function __construct(private string $defaultLocale = 'en')
  21. {
  22. }
  23. public function onKernelRequest(RequestEvent $event): void
  24. {
  25. $request = $event->getRequest();
  26. if (!$request->hasPreviousSession()) {
  27. return;
  28. }
  29. // try to see if the locale has been set as a _locale routing parameter
  30. if ($request->attributes->has('_locale')) {
  31. $locale = (string) $request->attributes->get('_locale');
  32. $request->getSession()->set('_locale', $locale);
  33. return;
  34. }
  35. // if no explicit locale has been set on this request, use one from the session
  36. $request->setLocale((string) $request->getSession()->get('_locale', $this->defaultLocale));
  37. }
  38. public static function getSubscribedEvents(): array
  39. {
  40. return [
  41. // must be registered before (i.e. with a higher priority than) the default Locale listener
  42. KernelEvents::REQUEST => [['onKernelRequest', 20]],
  43. ];
  44. }
  45. }