src/Profile/EventSubscriber/AccessDeniedSubscriber.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\Profile\EventSubscriber;
  3. use App\Profile\LinkGenerator\ProfileLinkGenerator;
  4. use App\Profile\Model\Profile;
  5. use App\Profile\Model\ProfileRoles;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\RedirectResponse;
  8. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  11. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  12. use Symfony\Component\Security\Core\Security;
  13. class AccessDeniedSubscriber implements EventSubscriberInterface
  14. {
  15.   public function __construct(
  16.     private ProfileLinkGenerator $profileLinkGenerator,
  17.     private UrlGeneratorInterface $urlGenerator,
  18.     private Security $security,
  19.   ) {
  20.   }
  21.   public static function getSubscribedEvents(): array
  22.   {
  23.     return [
  24.             KernelEvents::EXCEPTION => ['onKernelException'2],
  25.         ];
  26.   }
  27.   public function onKernelException(ExceptionEvent $event)
  28.   {
  29.     $exception $event->getThrowable();
  30.     if (!$exception instanceof AccessDeniedException) {
  31.       return;
  32.     }
  33.     $conditions $exception->getAttributes();
  34.     // dd($this->accessMap->getPatterns($event->getRequest()));
  35.     if (in_array('IS_ANONYMOUS'$conditions)) {
  36.       /** @var Profile */
  37.       $user $this->security->getUser();
  38.       $event->setResponse(new RedirectResponse($this->profileLinkGenerator->generate($user)));
  39.     } elseif (in_array(ProfileRoles::ROLE_USER$conditions)) {
  40.       $event->setResponse(new RedirectResponse($this->urlGenerator->generate('auth_login')));
  41.     } elseif (in_array('ROLE_PIMCORE_USER'$conditions)) {
  42.       $event->setResponse(new RedirectResponse('/admin/login'));
  43.     }
  44.   }
  45. }