<?php
namespace App\Api\EventListener;
use App\Api\Event\ImportEvent;
use App\Entity\Sale;
use App\Entity\SaleEvent;
use App\Entity\Vehicle;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Symfony\Component\Process\PhpProcess;
use Symfony\Component\Process\Process;
class ImportListener
{
public function __construct(private readonly string $projectDir, private readonly string $env, private readonly EntityManager $em)
{
}
/**
* Event call on push from etincelle.
*/
public function onPushedData(ImportEvent $event): void
{
$this->processSale($event);
}
/**
* Event call when last vehicle has been managed.
*/
public function onLastData(ImportEvent $event): void
{
$entity = $event->getObject();
if ($entity instanceof Vehicle) {
$this->generateFlyers($entity->getSale());
}
}
/**
* Event call when a sale is imported.
*/
public function onPersistedData(ImportEvent $event): void
{
$this->processVehicles($event);
}
/**
* General post-treatment.
*/
public function onEnd(): void
{
$this->cleanEvents();
}
/**
* import sale.
*/
protected function processSale(ImportEvent $event)
{
// launch sale import in a new process
$process = Process::fromShellCommandline('nohup php '.$this->projectDir.'/bin/console vpauto:etincelle:import sale '.$event->getObject().' --env='.$this->env.' > /dev/null 2>&1 &');
$process->run();
}
/**
* Import vehicles.
*/
protected function processVehicles(ImportEvent $event)
{
$entity = $event->getObject();
if ($entity instanceof Sale) {
$process = Process::fromShellCommandline('nohup php '.$this->projectDir.'/bin/console vpauto:etincelle:import vehicles '.$entity->getId().' --env='.$this->env.' > /dev/null 2>&1 &');
$process->run();
}
}
/**
* Generate flyers.
*/
protected function generateFlyers(Sale $sale)
{
$process = Process::fromShellCommandline('nohup php '.$this->projectDir.'/bin/console vpauto:generate:flyer '.$sale->getId().' --force --env='.$this->env.' > /dev/null 2>&1 &');
$process->run();
}
protected function cleanEvents()
{
$events = $this->em->getRepository(SaleEvent::class)->findAllInFutureSales();
foreach ($events as $event) {
if ($event->isEmpty()) {
foreach ($event->getVehicles() as $vehicle) {
$this->em->remove($vehicle);
}
$this->em->flush();
$this->em->remove($event);
}
}
$this->em->flush();
}
}