<?php
namespace App\Profile\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Security;
class ClubAccessDeniedRedirectEventSubscriber implements EventSubscriberInterface
{
public function __construct(
private UrlGeneratorInterface $urlGenerator,
private Security $security
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::EXCEPTION => ['onKernelException', 2],
];
}
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
if (!$exception instanceof AccessDeniedException) {
return;
}
// Check if Access Exception was because of a ROLE_CLUB* Role
$roles = $exception->getAttributes();
if (!array_filter($roles, fn ($role) => str_starts_with($role, 'ROLE_CLUB'))) {
return;
}
$conditions = $exception->getAttributes();
if (in_array('ROLE_PIMCORE_USER', $conditions)) {
$event->setResponse(new RedirectResponse('/admin/login'));
}
$event->setResponse(new RedirectResponse($this->urlGenerator->generate('profile_club_index')));
}
}