<?php
namespace App\EventSubscriber\Validation\Operation;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Operation\Coupon;
use App\Entity\Operation\Draw;
use App\Entity\Operation\Odr;
use App\Entity\Operation\Operation;
use App\Entity\Operation\Step;
use App\Entity\User\User;
use Exception;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
final class OperationSubscriber implements EventSubscriberInterface
{
private $user;
private AuthorizationCheckerInterface $authChecker;
public function __construct(TokenStorageInterface $tokenStorage, AuthorizationCheckerInterface $authChecker)
{
if (!$tokenStorage->getToken()) {
return;
}
$this->user = $tokenStorage->getToken()->getUser();
$this->authChecker = $authChecker;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => [
['addOwner', EventPriorities::PRE_VALIDATE],
],
];
}
/**
* @throws Exception
*/
public function addOwner(ViewEvent $event)
{
$operation = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (
!$operation instanceof Operation ||
!in_array($method, [Request::METHOD_POST, Request::METHOD_PUT])) {
return;
}
if (!$this->user instanceof User) {
throw new Exception("Invalid User");
}
if (!$this->authChecker->isGranted("ROLE_ADMIN_SOGEC", $this->user)) {
throw new UnauthorizedHttpException("This user has no rights to create operations");
}
if (null === $this->user->getCompany()) {
throw new Exception("Invalid User");
}
$company = $this->user->getCompany();
$operation
->setCompany($company)
->setOwner($this->user);
}
}