<?php
namespace EToNBundle\CompilerPass;
use EToNBundle\Builder\EventToNotificationEmail;
use EToNBundle\Entity\EventToNotificationStore;
use EToNBundle\Repository\EventToNotificationStoreRepository;
use EToNBundle\Resolver\EventToNotificationResolver;
use Psr\Log\LoggerInterface;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Contracts\EventDispatcher\Event;
use Twig\Environment;
class EventToNotificationEventSubscriber
{
public function __construct(private EventToNotificationStoreRepository $notificationStoreRepository,
private LoggerInterface $logger,
private EventToNotificationResolver $resolver,
private MailerInterface $mailer,
private Environment $twig,
private string $mailFrom,
private ?string $template= null)
{}
public function onEvent(Event $event): void
{
$info= $this->resolver->get($event);
if($info){
$data = $this->notificationStoreRepository->findBy(["event" => $info->name, "isEnabled" => true]);
if($data){
/** @var EventToNotificationStore $item */
foreach ($data as $item) {
if($item->isEnabled()){
try {
$email= new EventToNotificationEmail($info, $item, $event);
$email->build($this->mailFrom);
if($this->template){
$view= $this->twig->render($this->template, [
"notifEmail" => $email,
"store" => $item,
"event" => $event,
]);
$email->html($view);
}
$this->mailer->send($email);
} catch (TransportExceptionInterface $e) {
$this->logger->error($e->getMessage(), $e->getTrace());
}
}
}
}
}
}
}