src/EventSubscriber/Api/PositionTotalUpdateSubscriber.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\Api;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Roothirsch\ShopBundle\Entity\EstimatePosition;
  6. use Roothirsch\ShopBundle\Entity\OrderPosition;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpKernel\Event\ViewEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. class PositionTotalUpdateSubscriber implements EventSubscriberInterface
  12. {
  13. private $entityManager;
  14. public function __construct(EntityManagerInterface $entityManager)
  15. {
  16. $this->entityManager = $entityManager;
  17. }
  18. public static function getSubscribedEvents()
  19. {
  20. return [
  21. KernelEvents::VIEW => [
  22. ['updateParentTotal', EventPriorities::POST_WRITE],
  23. ],
  24. ];
  25. }
  26. public function updateParentTotal(ViewEvent $event): void
  27. {
  28. $entity = $event->getControllerResult();
  29. $method = $event->getRequest()->getMethod();
  30. // For position changes, update the parent entity's total
  31. if (($entity instanceof EstimatePosition || $entity instanceof OrderPosition)
  32. && in_array($method, [Request::METHOD_POST, Request::METHOD_PUT, Request::METHOD_DELETE])) {
  33. if ($entity instanceof EstimatePosition) {
  34. $parent = $entity->getEstimate();
  35. if ($parent) {
  36. // Force recalculation and save
  37. $parent->setTotal($parent->calculateTotal());
  38. $this->entityManager->persist($parent);
  39. $this->entityManager->flush();
  40. }
  41. } else if ($entity instanceof OrderPosition) {
  42. $parent = $entity->getOrder();
  43. if ($parent) {
  44. // Force recalculation and save
  45. $parent->setTotal($parent->calculateTotal());
  46. $this->entityManager->persist($parent);
  47. $this->entityManager->flush();
  48. }
  49. }
  50. }
  51. }
  52. }