<?php
namespace App\EventSubscriber;
use App\Controller\Front\AgeVerificationControllerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class AgeVerificationSubscriber implements EventSubscriberInterface
{
private UrlGeneratorInterface $urlGenerator;
public function __construct(UrlGeneratorInterface $urlGenerator)
{
$this->urlGenerator = $urlGenerator;
}
public function onKernelController(ControllerEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
if (strtolower($_ENV['APP_ENV']) === 'prod' || true) {
$controller = $event->getController();
$method = null;
// when a controller class defines multiple action methods, the controller
// is returned as [$controllerInstance, 'methodName']
if (is_array($controller)) {
$method = $controller[1];
$controller = $controller[0];
}
if ($controller instanceof AgeVerificationControllerInterface) {
$request = $event->getRequest();
$session = $request->getSession();
if (!$session->has('age_verification')) {
$url = $this->urlGenerator->generate('frontend_age_verification_index');
$event->setController(function () use ($url) {
return new RedirectResponse($url);
});
}
}
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
}