<?php
// api/src/EventSubscriber/BookMailSubscriber.php
namespace Roothirsch\ShopBundle\EventSubscriber\Api;
use ApiPlatform\Core\EventListener\EventPriorities;
use Roothirsch\CoreBundle\Entity\Company;
use Roothirsch\CoreBundle\Entity\User;
use Roothirsch\ShopBundle\Entity\Estimate;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
final class EstimateDistributorSubscriber implements EventSubscriberInterface
{
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
/**
* @var User
*/
private $user;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['validate', EventPriorities::PRE_VALIDATE],
];
}
public function validate(\Symfony\Component\HttpKernel\Event\ViewEvent $event)
{
/** @var Estimate $estimate */
$estimate = $event->getControllerResult();
if (!$estimate instanceof Estimate) {
return;
}
if ($estimate->getDistributor() !== null) {
return;
}
$this->user = $this->tokenStorage->getToken()->getUser();
if (!$this->user->getCompany() instanceof Company) {
return;
}
$event->getControllerResult()->setDistributor($this->user->getCompany()->getDistributor());
}
}