<?php
// api/src/EventSubscriber/BookMailSubscriber.php
namespace App\EventSubscriber\Api;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Company;
use App\Entity\Legacy\Estimate;
use App\Entity\User;
use App\Repository\EstimateRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
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;
/**
* @var EstimateRepository
*/
private $estimateRepository;
public function __construct(TokenStorageInterface $tokenStorage, EstimateRepository $estimateRepository)
{
$this->tokenStorage = $tokenStorage;
$this->estimateRepository = $estimateRepository;
}
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
&& $this->user->getCompany()->getDistributor() instanceof Company) {
$event->getControllerResult()->setDistributor($this->user->getCompany()->getDistributor());
return;
}
$q = $this->estimateRepository->createQueryBuilder('e');
$q->where('e.distributor IS NOT NULL AND e.status = :status')
->orderBy('e.updated', 'DESC')
->setMaxResults(1)
->setParameter('status', 'order');
$previousOrderWithDistributor = $q->getQuery()->getOneOrNullResult();
if ($previousOrderWithDistributor instanceof Estimate
&& $previousOrderWithDistributor->getDistributor() instanceof Company) {
$event->getControllerResult()->setDistributor($previousOrderWithDistributor->getDistributor());
}
}
}