<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Order\Order;
use App\Entity\Order\OrderLine;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class OrderAmountAndVtaSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['updateOrder', EventPriorities::PRE_WRITE],
];
}
/**
* @return void
*/
public function updateOrder(ViewEvent $args)
{
$entity = $args->getControllerResult();
if ($entity instanceof Order) {
$total = 0;
$entity->getOrderLines()->map(function (OrderLine $orderLine) use (&$total) {
$total += $orderLine->getAmount();
});
$entity
->setAmount((string) $total)
->setVat((string) ($total * Order::VTA_PERCENT / 100))
;
}
}
}