<?php
namespace App\EventSubscriber;
use App\Controller\District\ApplicationController;
use App\Controller\District\ProjectController;
use App\Controller\Helper\ActiveApplicationController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Security;
class ActiveApplicationListener implements \Symfony\Component\EventDispatcher\EventSubscriberInterface
{
// not needed anymore because of voters ?
private Security $security;
private Session $session;
private RouterInterface $router;
public function __construct(Security $security, SessionInterface $session, RouterInterface $router)
{
$this->security = $security;
$this->session = $session;
$this->router = $router;
}
public function onKernelController(ControllerEvent $event)
{
$controller = $event->getController();
// when a controller class defines multiple action methods, the controller
// is returned as [$controllerInstance, 'methodName']
if (is_array($controller)) {
$controllerClass = $controller[0];
$controllerMethod = $controller[1];
} else {
$controllerClass = $controller;
}
if ($controllerClass instanceof ActiveApplicationController) {
if (
($controllerClass instanceof ProjectController) ||
($controllerClass instanceof ApplicationController && ($controllerMethod == 'editApplication'))
) {
if (!$this->security->getUser()->getDistrict()->getActiveApplication()) {
$redirectUrl = $this->router->generate('app_district');
$event->setController(function () use ($redirectUrl) {
return new RedirectResponse($redirectUrl);
});
}
}
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
}