vendor/symfony/http-kernel/EventListener/LocaleAwareListener.php line 40

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <[email protected]>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\EventListener;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\HttpFoundation\RequestStack;
  13. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  14. use Symfony\Component\HttpKernel\Event\RequestEvent;
  15. use Symfony\Component\HttpKernel\KernelEvents;
  16. use Symfony\Contracts\Translation\LocaleAwareInterface;
  17. /**
  18. * Pass the current locale to the provided services.
  19. *
  20. * @author Pierre Bobiet <[email protected]>
  21. */
  22. class LocaleAwareListener implements EventSubscriberInterface
  23. {
  24. private $localeAwareServices;
  25. private $requestStack;
  26. /**
  27. * @param iterable<mixed, LocaleAwareInterface> $localeAwareServices
  28. */
  29. public function __construct(iterable $localeAwareServices, RequestStack $requestStack)
  30. {
  31. $this->localeAwareServices = $localeAwareServices;
  32. $this->requestStack = $requestStack;
  33. }
  34. public function onKernelRequest(RequestEvent $event): void
  35. {
  36. $this->setLocale($event->getRequest()->getLocale(), $event->getRequest()->getDefaultLocale());
  37. }
  38. public function onKernelFinishRequest(FinishRequestEvent $event): void
  39. {
  40. if (null === $parentRequest = $this->requestStack->getParentRequest()) {
  41. foreach ($this->localeAwareServices as $service) {
  42. $service->setLocale($event->getRequest()->getDefaultLocale());
  43. }
  44. return;
  45. }
  46. $this->setLocale($parentRequest->getLocale(), $parentRequest->getDefaultLocale());
  47. }
  48. public static function getSubscribedEvents()
  49. {
  50. return [
  51. // must be registered after the Locale listener
  52. KernelEvents::REQUEST => [['onKernelRequest', 15]],
  53. KernelEvents::FINISH_REQUEST => [['onKernelFinishRequest', -15]],
  54. ];
  55. }
  56. private function setLocale(string $locale, string $defaultLocale): void
  57. {
  58. foreach ($this->localeAwareServices as $service) {
  59. try {
  60. $service->setLocale($locale);
  61. } catch (\InvalidArgumentException $e) {
  62. $service->setLocale($defaultLocale);
  63. }
  64. }
  65. }
  66. }