<?php
namespace App\EventSubscriber\Api;
use ApiPlatform\Core\EventListener\EventPriorities;
use Doctrine\ORM\EntityManagerInterface;
use Roothirsch\ShopBundle\Entity\EstimatePosition;
use Roothirsch\ShopBundle\Entity\OrderPosition;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class PositionTotalUpdateSubscriber implements EventSubscriberInterface
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => [
['updateParentTotal', EventPriorities::POST_WRITE],
],
];
}
public function updateParentTotal(ViewEvent $event): void
{
$entity = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
// For position changes, update the parent entity's total
if (($entity instanceof EstimatePosition || $entity instanceof OrderPosition)
&& in_array($method, [Request::METHOD_POST, Request::METHOD_PUT, Request::METHOD_DELETE])) {
if ($entity instanceof EstimatePosition) {
$parent = $entity->getEstimate();
if ($parent) {
// Force recalculation and save
$parent->setTotal($parent->calculateTotal());
$this->entityManager->persist($parent);
$this->entityManager->flush();
}
} else if ($entity instanceof OrderPosition) {
$parent = $entity->getOrder();
if ($parent) {
// Force recalculation and save
$parent->setTotal($parent->calculateTotal());
$this->entityManager->persist($parent);
$this->entityManager->flush();
}
}
}
}
}