<?php declare(strict_types=1);
namespace Acris\MailerSalesChannel\Core\Content\Mail\Subscriber;
use Acris\MailerSalesChannel\Core\Content\Mail\Acris_Esmtp\Acris_EsmtpTransport;
use Acris\MailerSalesChannel\Core\Content\Mail\Service\Mailer;
use Acris\MailerSalesChannel\Core\Content\Mail\Service\Transport\Transports;
use Shopware\Core\Content\MailTemplate\Exception\MailEventConfigurationException;
use Shopware\Core\Content\MailTemplate\Exception\SalesChannelNotFoundException;
use Shopware\Core\Content\MailTemplate\MailTemplateActions;
use Shopware\Core\Content\MailTemplate\Service\Event\MailBeforeSentEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Exception\InconsistentCriteriaIdsException;
use Shopware\Core\Framework\Event\FlowEvent;
use Shopware\Core\Framework\Event\MailActionInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class MailSendSubscriber implements EventSubscriberInterface
{
public const ACTION_NAME = MailTemplateActions::MAIL_TEMPLATE_MAIL_SEND_ACTION;
/**
* @var Mailer
*/
private $mailer;
public function __construct(
Mailer $mailer
) {
$this->mailer = $mailer;
}
public static function getSubscribedEvents(): array
{
return [
self::ACTION_NAME => [
['sendMail', 1000]
],
MailBeforeSentEvent::class => 'beforeSendMail'
];
}
/**
* @throws MailEventConfigurationException
* @throws SalesChannelNotFoundException
* @throws InconsistentCriteriaIdsException
*/
public function sendMail($event): void
{
if ($event instanceof FlowEvent) {
$mailEvent = $event->getEvent();
if (!$mailEvent instanceof MailActionInterface) {
throw new MailEventConfigurationException('Not a instance of MailActionInterface', get_class($mailEvent));
}
if (empty($mailEvent->getSalesChannelId()) === false && $this->mailer instanceof Mailer && $this->mailer->getTransport() instanceof Transports) {
foreach ($this->mailer->getTransport()->getTransports() as $transport) {
if ($transport instanceof Acris_EsmtpTransport) {
$transport->recreateFromSwConfig($mailEvent->getSalesChannelId());
}
}
}
}
}
/**
* Event needed if mail is sent from state change from admin or api
* @param MailBeforeSentEvent $event
*/
public function beforeSendMail(MailBeforeSentEvent $event)
{
$data = $event->getData();
if(array_key_exists('salesChannelId', $data) && $data['salesChannelId'] && $this->mailer instanceof Mailer && $this->mailer->getTransport() instanceof Transports) {
foreach ($this->mailer->getTransport()->getTransports() as $transport) {
if ($transport instanceof Acris_EsmtpTransport && (empty($transport->getSalesChannelId()) === true || $transport->getSalesChannelId() !== $data['salesChannelId'])) {
$transport->recreateFromSwConfig($data['salesChannelId']);
}
}
}
}
}