<?php
declare(strict_types=1);
namespace App\Bundles\DiseaseCaseBundle\EventListener;
use App\Platform\Service\SessionProvider;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\RouterInterface;
#[AsEventListener]
class DiseaseCasePermissionExceptionEventListener
{
public function __construct(
private readonly RequestStack $requestStack,
private readonly RouterInterface $urlGenerator,
private readonly SessionProvider $sessionProvider,
) {
}
public function __invoke(ExceptionEvent $event): void
{
if (!$event->getThrowable() instanceof AccessDeniedHttpException) {
return;
}
if (!$request = $this->requestStack->getMainRequest()) {
return;
}
if (!$request->attributes->get('diseaseCase')) {
return;
}
/** @var \Symfony\Component\HttpFoundation\Session\Session $session */
$session = $this->sessionProvider->provide();
$session->getFlashBag()->add('permission_denied', '');
$referer = $request->headers->get('referer');
if ($referer && $this->possibleRedirects($referer)) {
$event->setResponse(new RedirectResponse($referer));
return;
}
$event->setResponse(new RedirectResponse($this->urlGenerator->generate('disease-cases.index')));
}
public function possibleRedirects(string $referer): bool
{
return str_contains($referer, 'patients') ||
str_contains($referer, 'outbreaks');
}
}