<?php
namespace App\EventListener;
use App\Component\Configuration\Util\Config;
use App\Entity\Subscription;
use App\Event\ContactSubmitEvent;
use App\Event\NewsletterEvent;
use App\Sendgrid\MailerInterface;
use App\Util\StringToEntityUtil;
use Doctrine\ORM\EntityManagerInterface;
use Gedmo\Translatable\TranslatableListener;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class ContactListener extends FormSubmitEventListener
{
/**
* @var EntityManagerInterface
*/
private $em;
/**
* @var EventDispatcherInterface
*/
private $eventDispatcher;
/**
* ContactListener constructor.
*/
public function __construct(
EntityManagerInterface $em,
EventDispatcherInterface $eventDispatcher,
MailerInterface $mailer,
ParameterBagInterface $parameterBag,
StringToEntityUtil $stringToEntityUtil,
?TranslatableListener $translatableListener,
Config $config
) {
parent::__construct($mailer, $parameterBag, $stringToEntityUtil, $translatableListener, $config);
$this->em = $em;
$this->eventDispatcher = $eventDispatcher;
}
public function postContactSubmit(ContactSubmitEvent $event)
{
$contact = $event->getContact();
$siteRecipient = $this->config->get('site_contact_custom_system_recipient') ?:
$this->parameterBag->get('site_company_email_address')
;
if ($event->getSendToEntity() && $event->getSendToId()) {
try {
$className = $this->stringToEntityUtil->classByTag($event->getSendToEntity());
$entity = $this->stringToEntityUtil->stringToEntity($className.':'.$event->getSendToId());
$siteRecipient = $entity->getEmail();
} catch (\Exception $exception) {
}
}
if ($siteOwnerMail = $this->getMail('site_contact_mail_site_owner')) {
if ($contact->getContactedCompany()) {
$siteRecipient = $contact->getContactedCompany()->getEmail() ?? $siteRecipient;
}
$this->mailer->mail(
$siteOwnerMail,
$this->getCompanyEmailSender(),
[$siteRecipient],
['contact' => $contact]
);
}
if ($visitorMail = $this->getMail('site_contact_mail_visitor')) {
$senderEmail = $this->config->get('site_contact_sender_mail') ?: $this->config->get('site_company_email_address');
$senderName = $this->config->get('site_contact_sender_name') ?: $this->config->get('site_company_name');
$this->mailer->mail(
$visitorMail,
[$senderEmail => $senderName],
[$contact->getEmail()],
['contact' => $contact]
);
}
if ($event->getForm() && $event->getForm()->has('subscribeToNewsletter') && $event->getForm()->get('subscribeToNewsletter')->getData()) {
$emailSubscription = (new Subscription())->setEmail($contact->getEmail());
$this->em->persist($emailSubscription);
$this->em->flush();
$this->eventDispatcher->dispatch(new NewsletterEvent($contact->getEmail()), NewsletterEvent::SUBSCRIBED);
}
}
}