<?php declare(strict_types=1);
namespace SmsBecoTechnicTheme\Subscriber;
use Shopware\Core\Checkout\Customer\CustomerEntity;
use Shopware\Core\Content\MailTemplate\MailTemplateEntity;
use Shopware\Core\Content\MailTemplate\Service\Event\MailBeforeValidateEvent;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class MailSubscriber implements EventSubscriberInterface
{
private EntityRepository $customerRepository;
private EntityRepository $mailTemplateRepository;
public function __construct(
EntityRepository $customerRepository,
EntityRepository $mailTemplateRepository
)
{
$this->customerRepository = $customerRepository;
$this->mailTemplateRepository = $mailTemplateRepository;
}
public static function getSubscribedEvents(): array
{
return [
MailBeforeValidateEvent::class => 'onMailBeforeValidateEvent',
];
}
public function onMailBeforeValidateEvent(MailBeforeValidateEvent $event)
{
//Get the keys of the recipients in data array
$recipients = array_keys($event->getData()['recipients']);
foreach ($recipients as $recipient) {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('email', $recipient));
/** @var CustomerEntity|null $customer */
$customer = $this->customerRepository->search($criteria, $event->getContext())->first();
if (!is_null($customer) && $event->getContext()->getLanguageId() !== $customer->getLanguageId()) {
$context = new Context(
$event->getContext()->getSource(),
$event->getContext()->getRuleIds(),
$event->getContext()->getCurrencyId(),
[$customer->getLanguageId()],
$event->getContext()->getVersionId(),
$event->getContext()->getCurrencyFactor(),
$event->getContext()->considerInheritance(),
$event->getContext()->getTaxState(),
$event->getContext()->getRounding()
);
$mailTemplateCriteria = new Criteria([$event->getData()['templateId']]);
/** @var MailTemplateEntity $mailTemplate */
$mailTemplate = $this->mailTemplateRepository->search($mailTemplateCriteria, $context)->first();
$data = $event->getData();
$data['contentHtml'] = $mailTemplate->getContentHtml();
$data['subject'] = $mailTemplate->getSubject();
$event->setData($data);
}
}
}
}