src/Profile/EventSubscriber/ClubAccessDeniedRedirectEventSubscriber.php line 28

Open in your IDE?
  1. <?php
  2. namespace App\Profile\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  8. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  9. use Symfony\Component\Security\Core\Security;
  10. class ClubAccessDeniedRedirectEventSubscriber implements EventSubscriberInterface
  11. {
  12.   public function __construct(
  13.     private UrlGeneratorInterface $urlGenerator,
  14.     private Security $security
  15.   ) {
  16.   }
  17.   public static function getSubscribedEvents(): array
  18.   {
  19.     return [
  20.             KernelEvents::EXCEPTION => ['onKernelException'2],
  21.         ];
  22.   }
  23.   public function onKernelException(ExceptionEvent $event)
  24.   {
  25.     $exception $event->getThrowable();
  26.     if (!$exception instanceof AccessDeniedException) {
  27.       return;
  28.     }
  29.     // Check if Access Exception was because of a ROLE_CLUB* Role
  30.     $roles $exception->getAttributes();
  31.     if (!array_filter($roles, fn ($role) => str_starts_with($role'ROLE_CLUB'))) {
  32.       return;
  33.     }
  34.     $conditions $exception->getAttributes();
  35.     if (in_array('ROLE_PIMCORE_USER'$conditions)) {
  36.       $event->setResponse(new RedirectResponse('/admin/login'));
  37.     }
  38.     $event->setResponse(new RedirectResponse($this->urlGenerator->generate('profile_club_index')));
  39.   }
  40. }