src/EventSubscriber/ItemEditableEventSubscriber.php line 46

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use ApiPlatform\Core\EventListener\EventPriorities;
  5. use App\Entity\Item;
  6. use App\Entity\User;
  7. use App\Enum\RoleEnum;
  8. use App\Exception\ItemEditableException;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpKernel\Event\ViewEvent;
  12. use Symfony\Component\HttpKernel\KernelEvents;
  13. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  14. final class ItemEditableEventSubscriber implements EventSubscriberInterface
  15. {
  16.     private array $allowedEditableRoles = [
  17.         RoleEnum::PROJECT_MANAGER,
  18.         RoleEnum::PROJECT_EMPLOYEE,
  19.         RoleEnum::EXTERNAL_PARTNER
  20.     ];
  21.     private array $allowedEditableMethods = [
  22.         Request::METHOD_POST,
  23.         Request::METHOD_PUT,
  24.         Request::METHOD_DELETE
  25.     ];
  26.     public function __construct(private readonly TokenStorageInterface $tokenStorage)
  27.     {
  28.     }
  29.     public static function getSubscribedEvents(): array
  30.     {
  31.         return [
  32.             KernelEvents::VIEW => ['isEditableDependOnRole'EventPriorities::PRE_WRITE]
  33.         ];
  34.     }
  35.     /**
  36.      * @throws ItemEditableException
  37.      */
  38.     public function isEditableDependOnRole(ViewEvent $event): void
  39.     {
  40.         $entity $event->getControllerResult();
  41.         if (
  42.             !$entity instanceof Item
  43.             ||
  44.             !in_array($event->getRequest()->getMethod(), $this->allowedEditableMethods)
  45.         ) {
  46.             return;
  47.         }
  48.         /** @var User $user */
  49.         $user $this->tokenStorage->getToken()->getUser();
  50.         if (!$user->getCurrentRole()) {
  51.             throw ItemEditableException::forUserDoesNotHaveCurrentRole();
  52.         }
  53.         if (!in_array($user->getCurrentRole()->getKeyName(), $this->allowedEditableRoles)) {
  54.             throw ItemEditableException::forUserDoesNotHavePermission();
  55.         }
  56.     }
  57. }