<?php
namespace Aqarmap\Bundle\MainBundle\EventListener;
use Aqarmap\Bundle\MainBundle\Adapter\MailerServiceInterface;
use Aqarmap\Bundle\MainBundle\Event\FeedbackEvent;
use Aqarmap\Bundle\MainBundle\Helpers\MailerHelper;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;
class FeedbackListener implements EventSubscriberInterface
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* @var MailerServiceInterface
*/
protected $mailer;
/**
* @var EntityManagerInterface
*/
private $entityManager;
/**
* @var TranslatorInterface
*/
private $translator;
private Environment $twigEngine;
/** @var MailerHelper */
private $mailerHelper;
public function __construct(
ContainerInterface $container,
EntityManagerInterface $entityManager,
TranslatorInterface $translator,
Environment $twigEngine,
MailerServiceInterface $mailer,
MailerHelper $mailerHelper
) {
$this->container = $container;
$this->entityManager = $entityManager;
$this->translator = $translator;
$this->twigEngine = $twigEngine;
$this->mailer = $mailer;
$this->mailerHelper = $mailerHelper;
}
public function onSubmitFeedback(FeedbackEvent $event): void
{
$feedback = $event->getFeedback();
$message = $this->getComposeMessage($feedback);
$this->getMailer()->sendMessage($message);
}
/**
* @return object
*/
public function getEntityManager()
{
return $this->entityManager;
}
/**
* @return MailerServiceInterface
*/
public function getMailer()
{
return $this->mailer;
}
/**
* @return TranslatorInterface
*/
public function getTranslator()
{
return $this->translator;
}
public function getTemplating(): Environment
{
return $this->twigEngine;
}
public static function getSubscribedEvents()
{
return [
'aqarmap.feedback.send_message' => ['onSubmitFeedback'],
];
}
/**
* @throws \Exception
*/
private function getComposeMessage($feedback)
{
$composeMessage = $this->mailerHelper->createMessageWithGlobalAttributes();
$composeMessage->setSubject(preg_replace('/\s+?(\S+)?$/', '', mb_substr($feedback->getMessage(), 0, 100)));
$composeMessage->setTo($this->container->getParameter('feedback_email'));
$composeMessage->setReplyTo($feedback->getEmail());
$composeMessage->setTemplate('@AqarmapMain/Feedback/Email/feedbackContent.html.twig');
$composeMessage->setTemplateContext(['feedback' => $feedback]);
$compose = $this->getMailer()->composeMessage($composeMessage);
$compose->getHeaders()->addTextHeader('X-Mail-Category', 'default-feedback');
$compose->getHeaders()->addTextHeader('X-Site-Country', $this->container->getParameter('country'));
return $compose;
}
}