<?php
namespace App\EventSubscriber;
use App\Entity\ProductLigneCommande;
use App\Event\Produit\LigneCommandeCreatedEvent;
use App\Event\Produit\LigneCommandeDeletedEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LigneCommandeSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents(): array
{
return [
LigneCommandeCreatedEvent::class => ['OnLigneCreated', 100],
LigneCommandeDeletedEvent::class => ['OnLigneDeleted', 100],
];
}
public function OnLigneCreated(LigneCommandeCreatedEvent $event)
{
$this->updateStock($event->getLigne());
}
public function OnLigneDeleted(LigneCommandeDeletedEvent $event)
{
$ligne = $event->getLigne();
$this->updateStock($ligne);
// Si lié a un BL, on met à jour le montant du BL
if ($ligne->getCommande()->getLivraisonChantier()) {
$livraison = $ligne->getCommande()->getLivraisonChantier();
$livraison->setTotalTtc($livraison->getTotalTtc() - $ligne->getTotalTtc());
$this->entityManager->flush();
}
}
private function updateStock (ProductLigneCommande $ligne) {
// On met à jour le montant HT et TTC de la commande
$commande = $ligne->getCommande();
$lignes = $commande->getLignes();
$ttc = $ht = 0;
foreach ($lignes as $l) {
$ttc += $l->getTotalTtc();
$ht += $l->getTotalHt();
}
$commande->setTotalHt($ht)->setTotalTtc($ttc);
$this->entityManager->persist($commande);
$this->entityManager->flush();
}
}