src/EventSubscriber/Content/LocalizationSubscriber.php line 26

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. private FormFactoryInterface $formFactory;
  13. private string $locale;
  14. public function __construct(string $locale, FormFactoryInterface $formFactory)
  15. {
  16. $this->locale = $locale;
  17. $this->formFactory = $formFactory;
  18. }
  19. public function onKernelRequest(RequestEvent $event): void
  20. {
  21. $form = $this->formFactory->create(LocaleForm::class, array('locale'=>$this->locale), array(
  22. 'action' =>$event->getRequest()->getUri(),
  23. 'method' => 'POST'
  24. ))->handleRequest($event->getRequest());
  25. if ($form->isSubmitted() && $form->isValid()) {
  26. // $referer = $event->getRequest()->headers->get('referer');
  27. $event->getRequest()->setLocale($form->getData()['locale']);
  28. }
  29. }
  30. public function onKernelController(ControllerEvent $event)
  31. {
  32. // $controller = $event->getController();
  33. /*
  34. * $controller passed can be either a class or a Closure.
  35. * This is not usual in Symfony but it may happen.
  36. * If it is a class, it comes in array format
  37. */
  38. // if (!is_array($controller)) {
  39. // return;
  40. // }
  41. }
  42. public static function getSubscribedEvents(): array
  43. {
  44. return [
  45. KernelEvents::REQUEST => [['onKernelRequest', 16]],
  46. KernelEvents::CONTROLLER => 'onKernelController',
  47. ];
  48. }
  49. }