<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Mandate;
use App\Exception\EmailException;
use App\Mailer\Mandate\MandateMailerInterface;
use App\Message\GenerateAdditionalPropertiesMandateMessage;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Messenger\MessageBusInterface;
use Psr\Log\LoggerInterface;
class MandateSubscriber implements EventSubscriberInterface
{
private MandateMailerInterface $mailer;
private MessageBusInterface $bus;
private LoggerInterface $logger;
/**
* @param MandateMailerInterface $mailer
* @param MessageBusInterface $bus
* @param LoggerInterface $logger
*/
public function __construct(
MandateMailerInterface $mailer,
MessageBusInterface $bus,
LoggerInterface $logger
){
$this->mailer = $mailer;
$this->bus = $bus;
$this->logger = $logger;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => [
['onPost', EventPriorities::POST_WRITE],
['onPut', EventPriorities::POST_WRITE]
]
];
}
/**
* @param ViewEvent $event
*
* @return void
*
* @throws EmailException
*/
public function onPost(ViewEvent $event): void
{
$mandate = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$mandate instanceof Mandate || Request::METHOD_POST !== $method) {
return;
}
if(empty($mandate->getProperty()->getRecommendation())){
return;
}
$this->mailer->notifyRecommended($mandate);
}
/**
* @param ViewEvent $event
*
* @return void
*
* @throws EmailException
*/
public function onPut(ViewEvent $event): void
{
$mandate = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$mandate instanceof Mandate || Request::METHOD_PUT !== $method) {
return;
}
$propertyIds = [];
foreach ($mandate->getAdditionalProperties()->getIterator() as $additionalProperty) {
$propertyIds[] = $additionalProperty->getId();
}
$mandateId = $mandate->getId();
try {
$message = new GenerateAdditionalPropertiesMandateMessage($mandateId, $propertyIds);
$this->bus->dispatch($message);
} catch (\Throwable $exception) {
$this->logger->error(
'Failed to publish GenerateAdditionalPropertiesMandateMessage !',
[
'trace' => $exception->getTrace(),
'line' => $exception->getLine(),
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
]
);
}
}
}