src/EventSubscriber/Api/EstimateDistributorSubscriber.php line 47

Open in your IDE?
  1. <?php
  2. // api/src/EventSubscriber/BookMailSubscriber.php
  3. namespace App\EventSubscriber\Api;
  4. use ApiPlatform\Core\EventListener\EventPriorities;
  5. use App\Entity\Company;
  6. use App\Entity\Legacy\Estimate;
  7. use App\Entity\User;
  8. use App\Repository\EstimateRepository;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\HttpKernel\Event\ViewEvent;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  13. final class EstimateDistributorSubscriber implements EventSubscriberInterface
  14. {
  15. /**
  16. * @var TokenStorageInterface
  17. */
  18. private $tokenStorage;
  19. /**
  20. * @var User
  21. */
  22. private $user;
  23. /**
  24. * @var EstimateRepository
  25. */
  26. private $estimateRepository;
  27. public function __construct(TokenStorageInterface $tokenStorage, EstimateRepository $estimateRepository)
  28. {
  29. $this->tokenStorage = $tokenStorage;
  30. $this->estimateRepository = $estimateRepository;
  31. }
  32. public static function getSubscribedEvents()
  33. {
  34. return [
  35. KernelEvents::VIEW => ['validate', EventPriorities::PRE_VALIDATE],
  36. ];
  37. }
  38. public function validate(\Symfony\Component\HttpKernel\Event\ViewEvent $event)
  39. {
  40. /** @var Estimate $estimate */
  41. $estimate = $event->getControllerResult();
  42. if (!$estimate instanceof Estimate) {
  43. return;
  44. }
  45. if ($estimate->getDistributor() !== null) {
  46. return;
  47. }
  48. $this->user = $this->tokenStorage->getToken()->getUser();
  49. if ($this->user->getCompany() instanceof Company
  50. && $this->user->getCompany()->getDistributor() instanceof Company) {
  51. $event->getControllerResult()->setDistributor($this->user->getCompany()->getDistributor());
  52. return;
  53. }
  54. $q = $this->estimateRepository->createQueryBuilder('e');
  55. $q->where('e.distributor IS NOT NULL AND e.status = :status')
  56. ->orderBy('e.updated', 'DESC')
  57. ->setMaxResults(1)
  58. ->setParameter('status', 'order');
  59. $previousOrderWithDistributor = $q->getQuery()->getOneOrNullResult();
  60. if ($previousOrderWithDistributor instanceof Estimate
  61. && $previousOrderWithDistributor->getDistributor() instanceof Company) {
  62. $event->getControllerResult()->setDistributor($previousOrderWithDistributor->getDistributor());
  63. }
  64. }
  65. }