src/EventSubscriber/AgeVerificationSubscriber.php line 44

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Controller\Front\AgeVerificationControllerInterface;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  9. class AgeVerificationSubscriber implements EventSubscriberInterface
  10. {
  11.     private UrlGeneratorInterface $urlGenerator;
  12.     public function __construct(UrlGeneratorInterface $urlGenerator)
  13.     {
  14.         $this->urlGenerator $urlGenerator;
  15.     }
  16.     public function onKernelController(ControllerEvent $event): void
  17.     {
  18.         if (!$event->isMainRequest()) {
  19.             return;
  20.         }
  21.         if (strtolower($_ENV['APP_ENV']) === 'prod' || true) {
  22.             $controller $event->getController();
  23.             $method null;
  24.             // when a controller class defines multiple action methods, the controller
  25.             // is returned as [$controllerInstance, 'methodName']
  26.             if (is_array($controller)) {
  27.                 $method $controller[1];
  28.                 $controller $controller[0];
  29.             }
  30.             if ($controller instanceof AgeVerificationControllerInterface) {
  31.                 $request $event->getRequest();
  32.                 $session $request->getSession();
  33.                 if (!$session->has('age_verification')) {
  34.                     $url $this->urlGenerator->generate('frontend_age_verification_index');
  35.                     $event->setController(function () use ($url) {
  36.                         return new RedirectResponse($url);
  37.                     });
  38.                 }
  39.             }
  40.         }
  41.     }
  42.     public static function getSubscribedEvents(): array
  43.     {
  44.         return [
  45.             KernelEvents::CONTROLLER => 'onKernelController',
  46.         ];
  47.     }
  48. }