<?php
/**
* @author Léo BANNHOLTZER (contact@scaledev.fr)
* @copyright 2021 - ScaleDEV SAS, 12 RUE CHARLES MORET, 10120 ST ANDRE LES VERGERS
* @license commercial
*/
declare(strict_types=1);
namespace Bluue\ShipmentsBundle\EventSubscriber\SalesBundle;
use Bluue\ProductsBundle\Repository\DeclinationRepository;
use Bluue\ProductsBundle\Repository\ProductRepository;
use Doctrine\ORM\EntityManagerInterface;
use Bluue\ShipmentsBundle\Entity\OrderOptions;
use Bluue\SalesBundle\Event\OrderMovementsEvent;
use Bluue\ShipmentsBundle\Repository\OrderOptionsRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface $em
*/
private EntityManagerInterface $em;
/**
* @var OrderOptionsRepository $orderOptionsRepo
*/
private OrderOptionsRepository $orderOptionsRepo;
/**
* @var DeclinationRepository $declinationRepo
*/
private DeclinationRepository $declinationRepo;
/**
* @var ProductRepository $productRepo
*/
private ProductRepository $productRepo;
public function __construct(
EntityManagerInterface $em,
OrderOptionsRepository $orderOptionsRepo,
DeclinationRepository $declinationRepo,
ProductRepository $productRepo
) {
$this->em = $em;
$this->orderOptionsRepo = $orderOptionsRepo;
$this->declinationRepo = $declinationRepo;
$this->productRepo = $productRepo;
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [OrderMovementsEvent::VALIDATE_ORDER => 'validateOrder'];
}
/**
* @param OrderMovementsEvent $event
* @return void
*/
public function validateOrder(OrderMovementsEvent $event): void
{
$order = $event->getOrder();
$order_options = $this->orderOptionsRepo->findOneBy(['order' => $order]);
if (!$order_options) {
$order_options = new OrderOptions();
$order_options->setOrder($order);
}
$order_weight = 0;
foreach ($order->getFilterLines(true, true) as $order_line) {
if ($order_line->getQuantity() > 0 && $element_id = $order_line->getElementId()) {
if ($order_line->hasDeclinationLinked()) {
$weight = $this->declinationRepo->find($element_id)->getWeight();
} else {
$weight = $this->productRepo->find($element_id)->getWeight();
}
$order_weight += (float) $weight * (float) $order_line->getQuantity();
}
}
$order_options->setWeight((string) $order_weight);
$order_options->setStatus(0);
$this->em->persist($order_options);
$this->em->flush();
}
}