src/EventSubscriber/CoordinatorAuthenticatedSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Enum\UserRole;
  4. use App\Enum\ErrorResponseMessageEnum;
  5. use App\Service\UserInterface;
  6. use App\Service\FrontendService;
  7. use App\Controller\CoordinatorAuthenticatedController;
  8. use App\Exception\RoleCoordinatorRequiredException;
  9. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  13. class CoordinatorAuthenticatedSubscriber implements EventSubscriberInterface
  14. {
  15.     private $userService;
  16.     private $frontendService;
  17.     
  18.     public function __construct(UserInterface $userServiceFrontendService $frontendService){
  19.         $this->userService $userService;
  20.         $this->frontendService $frontendService;
  21.     }
  22.     
  23.     public function onKernelController(ControllerEvent $event)
  24.     {
  25.         $controller $event->getController();
  26.         /*
  27.          * $controller passed can be either a class or a Closure.
  28.          * This is not usual in Symfony but it may happen.
  29.          * If it is a class, it comes in array format
  30.          */
  31.         if (!is_array($controller)) {
  32.             return;
  33.         }
  34.         if ($controller[0] instanceof CoordinatorAuthenticatedController) {
  35.             if (!$this->userService->isAccessGranted(UserRole::ROLE_COORDINATOR)){
  36.                 throw new RoleCoordinatorRequiredException();
  37.             }
  38.         }
  39.     }
  40.     public static function getSubscribedEvents()
  41.     {
  42.         return array(
  43.             KernelEvents::CONTROLLER => 'onKernelController',
  44.            KernelEvents::EXCEPTION => array(
  45.                array('roleCoordinatorRequiredException'0),
  46.            )            
  47.         );
  48.     }
  49.     
  50.     public function roleCoordinatorRequiredException(ExceptionEvent $event)
  51.     {
  52.         if ($event->getThrowable() instanceof RoleCoordinatorRequiredException){
  53.             $event->setResponse($this->frontendService->forbidden(ErrorResponseMessageEnum::ROLE_COORDINATOR_REQUIRED));
  54.         }
  55.     }    
  56. }