src/EventSubscriber/Expediting/FreightDocumentsUploadScheduler.php line 33
<?php
namespace App\EventSubscriber\Expediting;
use App\Event\Sales\WorkOrderCancelationEvent;
use App\Event\Sales\WorkOrderCreationEvent;
use App\Event\Sales\WorkOrderEventInterface;
use App\Event\Sales\WorkOrderReopeningEvent;
use App\EventSubscriber\TasksCancelerTrait;
use App\Repository\Scheduler\TaskRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
readonly class FreightDocumentsUploadScheduler implements EventSubscriberInterface
{
use TasksCancelerTrait;
public function __construct(
private EntityManagerInterface $entityManager,
private TaskRepository $taskRepository,
) {}
public static function getSubscribedEvents(): array
{
return [
WorkOrderCreationEvent::IDENTIFIER => ['handleScheduling', 80],
WorkOrderReopeningEvent::IDENTIFIER => ['handleScheduling', 80],
WorkOrderCancelationEvent::IDENTIFIER => ['handleCancelation', 80],
];
}
/** It is important to only execute this after work order is persisted and not after the freight entity is persisted */
public function handleScheduling(WorkOrderEventInterface $event): void
{
$workOrder = $event->getWorkOrder();
foreach ($workOrder->getFreights() as $freight) {
$documentsGatheringTask = $this->taskRepository->getDocumentsGatheringTask(freight: $freight, createIfNull: true);
$documentsRequestTask = $this->taskRepository->getDocumentsRequestTask(freight: $freight, createIfNull: true);
$this->entityManager->persist($documentsGatheringTask);
$this->entityManager->persist($documentsRequestTask);
}
$this->entityManager->flush();
}
/** It is important to only execute this after work order is persisted and not after the freight entity is persisted */
public function handleCancelation(WorkOrderEventInterface $event): void
{
$workOrder = $event->getWorkOrder();
$tasks = [];
foreach ($workOrder->getFreights() as $freight) {
$tasks []= $this->taskRepository->getDocumentsGatheringTask(freight: $freight);
$tasks []= $this->taskRepository->getDocumentsRequestTask(freight: $freight);
}
$this->cancelTasks($tasks);
$this->entityManager->flush();
}
}