src/EventSubscriber/Content/LocalizationSubscriber.php line 20

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\Content;
  3. use App\Form\Content\LocaleForm;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\Form\FormFactoryInterface;
  6. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  7. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  8. use Symfony\Component\HttpKernel\Event\RequestEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. class LocalizationSubscriber implements EventSubscriberInterface
  11. {
  12. public function __construct(private readonly string $locale, private readonly FormFactoryInterface $formFactory)
  13. {
  14. }
  15. public function onKernelRequest(RequestEvent $event): void
  16. {
  17. $form = $this->formFactory->create(LocaleForm::class, ['locale'=>$this->locale], [
  18. 'action' =>$event->getRequest()->getUri(),
  19. 'method' => 'POST'
  20. ])->handleRequest($event->getRequest());
  21. if ($form->isSubmitted() && $form->isValid()) {
  22. // $referer = $event->getRequest()->headers->get('referer');
  23. $event->getRequest()->setLocale($form->getData()['locale']);
  24. }
  25. }
  26. public function onKernelController(ControllerEvent $event): void
  27. {
  28. // $controller = $event->getController();
  29. /*
  30. * $controller passed can be either a class or a Closure.
  31. * This is not usual in Symfony but it may happen.
  32. * If it is a class, it comes in array format
  33. */
  34. // if (!is_array($controller)) {
  35. // return;
  36. // }
  37. }
  38. public static function getSubscribedEvents(): array
  39. {
  40. return [
  41. KernelEvents::REQUEST => [['onKernelRequest', 16]],
  42. KernelEvents::CONTROLLER => 'onKernelController',
  43. ];
  44. }
  45. }