<?php
namespace Gartencenter24Theme\Subscriber;
use Shopware\Core\Content\MailTemplate\Service\Event\MailBeforeSentEvent;
use Shopware\Core\Content\MailTemplate\Service\Event\MailBeforeValidateEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Mime\Address;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
class MailBeforeSentEventSubscriber implements EventSubscriberInterface
{
/**
* @var string|null
*/
private ?string $customerEmail = null;
/**
* @var string|null
*/
private ?string $customerName = null;
/**
* @var EntityRepositoryInterface
*/
private $mailTemplateRepository;
/**
* @param EntityRepositoryInterface $mailTemplateRepository
*/
public function __construct(EntityRepositoryInterface $mailTemplateRepository)
{
$this->mailTemplateRepository = $mailTemplateRepository;
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [
MailBeforeValidateEvent::class => 'onMailBeforeValidateEvent',
MailBeforeSentEvent::class => 'onMailBeforeSentEvent',
];
}
/**
* @param MailBeforeValidateEvent $event
* @return void
*/
public function onMailBeforeValidateEvent(MailBeforeValidateEvent $event)
{
if (
!array_key_exists('templateId', $event->getData())
|| !$this->checkMailTemplate($event->getData()['templateId'], $event->getContext())
) {
return;
}
$this->customerEmail = $event->getTemplateData()['contactFormData']['email'];
$this->customerName = $event->getTemplateData()['contactFormData']['firstName'] . ' ' . $event->getTemplateData()['contactFormData']['lastName'];
}
/**
* @param MailBeforeSentEvent $event
* @return void
*/
public function onMailBeforeSentEvent(MailBeforeSentEvent $event)
{
if (
!array_key_exists('templateId', $event->getData())
|| !$this->checkMailTemplate($event->getData()['templateId'], $event->getContext())
) {
return;
}
if ($this->customerEmail === null) {
return;
}
if ($this->customerEmail) {
$event->getMessage()->replyTo(new Address($this->customerEmail, $this->customerName));
}
}
/**
* @param string $templateId
* @param Context $context
* @return bool
*/
protected function checkMailTemplate (string $templateId, Context $context)
{
$criteria = new Criteria();
$criteria->addAssociation('mailTemplateType');
$criteria->addFilter(
new EqualsFilter('id', $templateId),
new EqualsFilter('mailTemplateType.technicalName', 'contact_form')
);
$template = $this->mailTemplateRepository->search($criteria, $context);
if ($template->getTotal() < 1) {
return false;
}
return true;
}
}