<?php
namespace App\Profile\EventSubscriber;
use App\Profile\LinkGenerator\ProfileLinkGenerator;
use App\Profile\Model\Profile;
use App\Profile\Model\ProfileRoles;
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 AccessDeniedSubscriber implements EventSubscriberInterface
{
public function __construct(
private ProfileLinkGenerator $profileLinkGenerator,
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;
}
$conditions = $exception->getAttributes();
// dd($this->accessMap->getPatterns($event->getRequest()));
if (in_array('IS_ANONYMOUS', $conditions)) {
/** @var Profile */
$user = $this->security->getUser();
$event->setResponse(new RedirectResponse($this->profileLinkGenerator->generate($user)));
} elseif (in_array(ProfileRoles::ROLE_USER, $conditions)) {
$event->setResponse(new RedirectResponse($this->urlGenerator->generate('auth_login')));
} elseif (in_array('ROLE_PIMCORE_USER', $conditions)) {
$event->setResponse(new RedirectResponse('/admin/login'));
}
}
}