src/EventSubscriber/Validation/Operation/OperationSubscriber.php line 48

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\Validation\Operation;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\Operation\Coupon;
  5. use App\Entity\Operation\Draw;
  6. use App\Entity\Operation\Odr;
  7. use App\Entity\Operation\Operation;
  8. use App\Entity\Operation\Step;
  9. use App\Entity\User\User;
  10. use Exception;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpKernel\Event\ViewEvent;
  14. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
  15. use Symfony\Component\HttpKernel\KernelEvents;
  16. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  17. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  18. final class OperationSubscriber implements EventSubscriberInterface
  19. {
  20.     private $user;
  21.     private AuthorizationCheckerInterface $authChecker;
  22.     public function __construct(TokenStorageInterface $tokenStorageAuthorizationCheckerInterface $authChecker)
  23.     {
  24.         if (!$tokenStorage->getToken()) {
  25.             return;
  26.         }
  27.         $this->user $tokenStorage->getToken()->getUser();
  28.         $this->authChecker $authChecker;
  29.     }
  30.     public static function getSubscribedEvents(): array
  31.     {
  32.         return [
  33.             KernelEvents::VIEW => [
  34.                 ['addOwner'EventPriorities::PRE_VALIDATE],
  35.             ],
  36.         ];
  37.     }
  38.     /**
  39.      * @throws Exception
  40.      */
  41.     public function addOwner(ViewEvent $event)
  42.     {
  43.         $operation $event->getControllerResult();
  44.         $method $event->getRequest()->getMethod();
  45.         if (
  46.             !$operation instanceof Operation ||
  47.             !in_array($method, [Request::METHOD_POSTRequest::METHOD_PUT])) {
  48.             return;
  49.         }
  50.         if (!$this->user instanceof User) {
  51.             throw new Exception("Invalid User");
  52.         }
  53.         if (!$this->authChecker->isGranted("ROLE_ADMIN_SOGEC"$this->user)) {
  54.             throw new UnauthorizedHttpException("This user has no rights to create operations");
  55.         }
  56.         if (null === $this->user->getCompany()) {
  57.             throw new Exception("Invalid User");
  58.         }
  59.         $company $this->user->getCompany();
  60.         $operation
  61.             ->setCompany($company)
  62.             ->setOwner($this->user);
  63.     }
  64. }