<?php declare(strict_types=1);
namespace System4ShopTheme\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Content\MailTemplate\Service\Event\MailBeforeSentEvent;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class MailSubscriber implements EventSubscriberInterface {
/**
* @var SystemConfigService
*/
private $systemConfigService;
/**
* @var EntityRepository
*/
private $templateRepository;
/**
* @param SystemConfigService $systemConfigService
* @param EntityRepository $templateRepository
*/
public function __construct(SystemConfigService $systemConfigService, EntityRepository $templateRepository)
{
$this->systemConfigService = $systemConfigService;
$this->templateRepository = $templateRepository;
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents(): array
{
return [
MailBeforeSentEvent::class => 'onMailSend'
];
}
/**
* @param MailBeforeSentEvent $event
* @return void
*/
public function onMailSend(MailBeforeSentEvent $event)
{
$salesChannelId = $event->getData()['salesChannelId'];
if (!$this->isConfigEmpty('customMailTemplates', $salesChannelId)) {
//if mail entity is selected in config
$template = $this->getTemplate($event);
if (in_array($template->getMailTemplateTypeId(), $this->getConfig('customMailTemplates', $salesChannelId))) {
$email = $this->getConfig("emailCc", $salesChannelId);
$event->getMessage()->addCc($email);
}
}
}
/**
* @param $path
* @param $salesChannelId
* @return array|bool|float|int|string|null
*/
private function getConfig($path, $salesChannelId) {
return $this->systemConfigService->get('System4ShopTheme.config.'.$path, $salesChannelId);
}
/**
* @param MailBeforeSentEvent $event
* @return mixed|null
*/
private function getTemplate(MailBeforeSentEvent $event) {
$templateId = $event->getData()['templateId'];
$templates = $this->templateRepository->search((new Criteria([$templateId])), $event->getContext());
return $templates->first();
}
/**
* @param $path
* @param $salesChannelId
* @return bool
*/
private function isConfigEmpty($path, $salesChannelId): bool
{
if(empty($this->getConfig($path, $salesChannelId))) {
return true;
}
return false;
}
}