<?php
namespace App\EventSubscriber\Validation;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Participation\Coupon;
use App\Entity\Participation\Odr;
use App\Entity\Participation\Participation;
use App\Entity\Participation\Refund;
use App\Entity\Participation\Step;
use App\Entity\User\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
final class ParticipationSubscriber 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 => [
['addCompany', EventPriorities::PRE_VALIDATE],
['setUser', EventPriorities::PRE_VALIDATE],
],
];
}
public function setUser(ViewEvent $event)
{
$part = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (
!$part instanceof Participation &&
!$part instanceof Coupon &&
!$part instanceof Refund &&
!$part instanceof Step ||
!$part instanceof Odr ||
!in_array($method, [Request::METHOD_POST, Request::METHOD_PUT])) {
return;
}
if(!$this->user instanceof User) {
throw new \Exception("Invalid User");
}
$part->setUser($this->user);
}
public function addCompany(ViewEvent $event)
{
$part = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (
!$part instanceof Participation &&
!$part instanceof Coupon &&
!$part instanceof Refund &&
!$part instanceof Step ||
!$part instanceof Odr ||
!in_array($method, [Request::METHOD_POST, Request::METHOD_PUT])) {
return;
}
if(!$this->user instanceof User) {
throw new \Exception("Invalid User");
}
if (null === $this->user->getCompany()) {
throw new \Exception("Invalid Company");
}
$company = $this->user->getCompany();
$part->setCompany($company);
}
}