src/EventsSubscriber/System/KernelEventsSubscriber.php line 35

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventsSubscriber\System;
  4. use App\Contracts\System\OnlyGuestController;
  5. use App\Contracts\User\Role;
  6. use App\Entity\User;
  7. use App\Services\Creator\Exception\AuthException;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  13. use Symfony\Component\Security\Core\Security;
  14. class KernelEventsSubscriber implements EventSubscriberInterface
  15. {
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             KernelEvents::CONTROLLER => [
  20.                 'onController',
  21.             ],
  22.         ];
  23.     }
  24.     public function __construct(
  25.         private readonly Security $security,
  26.         private readonly UrlGeneratorInterface $urlGenerator,
  27.     ) {
  28.     }
  29.     public function onController(ControllerEvent $event): void
  30.     {
  31.         /** @var User|null $user */
  32.         $user $this->security->getUser();
  33.         $controller $event->getController();
  34.         if (!is_array($controller) || $user === null) {
  35.             return;
  36.         }
  37.         if ($user->isBlocked() || $user->isDeleted()) {
  38.             throw new AuthException('You were removed from the platform'403);
  39.         }
  40.         if ($controller[0] instanceof OnlyGuestController) {
  41.             $route $this->security->isGranted(Role::CREATOR)
  42.                 ? 'creator-activity'
  43.                 'sponsor-campaign-list';
  44.             $event->setController(function () use ($route) {
  45.                 return new RedirectResponse($this->urlGenerator->generate($route));
  46.             });
  47.         }
  48.     }
  49. }