src/EventSubscriber/NeedsPermissionSubscriber.php line 45

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Annotation\NeedsPermission;
  4. use App\Security\PermissionsService;
  5. use Doctrine\Common\Annotations\Reader;
  6. use Psr\Cache\InvalidArgumentException;
  7. use ReflectionClass;
  8. use ReflectionException;
  9. use ReflectionMethod;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  12. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  13. use Symfony\Component\HttpKernel\KernelEvents;
  14. class NeedsPermissionSubscriber implements EventSubscriberInterface
  15. {
  16.     protected $annotationReader;
  17.     protected $permissionsService;
  18.     public function __construct(Reader $annotationReaderPermissionsService $permissionsService)
  19.     {
  20.         $this->annotationReader $annotationReader;
  21.         $this->permissionsService $permissionsService;
  22.     }
  23.     public static function getSubscribedEvents()
  24.     {
  25.         // return the subscribed events, their methods and priorities
  26.         return [
  27.             KernelEvents::CONTROLLER => [
  28.                 ['checkPermission'10],
  29.             ],
  30.         ];
  31.     }
  32.     /**
  33.      * @param ControllerEvent $event
  34.      * @throws InvalidArgumentException
  35.      * @throws ReflectionException
  36.      */
  37.     public function checkPermission(ControllerEvent $event)
  38.     {
  39.         $controller $event->getController();
  40.         if (!is_array($controller)) {
  41.             return;
  42.         }
  43.         $action = new ReflectionMethod($controller[0], $controller[1]);
  44.         $class = new ReflectionClass($controller[0]);
  45.         $annotation $this
  46.             ->annotationReader
  47.             ->getMethodAnnotation($actionNeedsPermission::class);
  48.         if (!$annotation) {
  49.             $annotation $this
  50.                 ->annotationReader
  51.                 ->getClassAnnotation($classNeedsPermission::class);
  52.         }
  53.         if (!($annotation instanceof NeedsPermission)) {
  54.             return;
  55.         }
  56.         $permission $annotation->permission;
  57.         $hasPermission $this->permissionsService->check($permission);
  58.         if (!$hasPermission) {
  59.             throw new AccessDeniedHttpException();
  60.         }
  61.     }
  62. }