<?php
namespace App\Api\EventListener;
use App\Api\Event\ImportEvent;
use App\Entity\User;
use App\Entity\Vehicle;
use App\Entity\VehicleAlert;
use App\Mailer\TranslatableMailer;
use Doctrine\ORM\EntityManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\Mailer\Exception\TransportException;
use Twig\Environment;
class ImportAlertListener
{
private $_em;
private $counter;
public function __construct(EntityManager $em, private readonly TranslatableMailer $mailer, private readonly Environment $templating, private readonly LoggerInterface $logger, private $from)
{
$this->_em = $em;
$this->counter['overall'] = 0;
}
public function onIgnoredData(ImportEvent $event): void
{
$data = $event->getObject();
if (isset($data->status) && 'D' === $data->status) {
if (null !== $vehicle = $this->_em->getRepository(Vehicle::class)->findOneByVehicleId($data->id)) {
if (Vehicle::SALING_STATE_SUPPRIME === $vehicle->getSalingState()) {
$this->counter['current'] = 0;
foreach ($vehicle->getAlerts() as $alert) {
$this->sendDeleted($alert->getUser(), $vehicle);
$this->_em->remove($alert);
++$this->counter['current'];
}
foreach ($vehicle->getSelections() as $selection) {
$this->_em->remove($selection);
}
$this->_em->flush();
$this->logger->info($this->counter['current'].' deletion alert(s) sent for this Vehicle.');
}
}
}
}
public function onPersistedData(ImportEvent $event): void
{
$entity = $event->getObject();
if ($entity instanceof Vehicle) {
$alerts = $entity->getAlerts();
$this->counter['current'] = 0;
foreach ($alerts as $alert) {
if ($entity->isStartingPriceAvailable() && $alert->getLastPrice() !== $entity->getStartingPrice()) {
$this->send($alert);
$alert->setLastPrice($entity->getStartingPrice());
$this->_em->flush($alert);
++$this->counter['current'];
++$this->counter['overall'];
}
}
$this->logger->info($this->counter['current'].' alert(s) sent for this Vehicle.');
}
}
public function onEnd(): void
{
$this->logger->info($this->counter['overall'].' alert(s) sent overall.');
}
private function send(VehicleAlert $alert): void
{
try {
$this->mailer->send(
$alert->getUser(),
'/Mail/alert_vehicle_price.html.twig',
['alert' => $alert]
);
} catch (TransportException $e) {
$this->logger->warning(sprintf('Couldn\'t sent email to %s. Error message : %s', $alert->getUser()->getEmail(), $e->getMessage()));
}
}
private function sendDeleted(User $user, Vehicle $vehicle): void
{
try {
$this->mailer->send(
$user,
'/Mail/alert_vehicle_deleted.html.twig',
['vehicle' => $vehicle]
);
} catch (TransportException $e) {
$this->logger->warning(sprintf('Couldn\'t sent email to %s. Error message : %s', $user->getEmail(), $e->getMessage()));
}
}
}