vendor/shopware/core/Content/MailTemplate/Subscriber/MailSendSubscriber.php line 93

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Content\MailTemplate\Subscriber;
  3. use Psr\Log\LoggerInterface;
  4. use Shopware\Core\Checkout\Document\DocumentService;
  5. use Shopware\Core\Content\MailTemplate\Exception\MailEventConfigurationException;
  6. use Shopware\Core\Content\MailTemplate\Exception\SalesChannelNotFoundException;
  7. use Shopware\Core\Content\MailTemplate\MailTemplateActions;
  8. use Shopware\Core\Content\MailTemplate\MailTemplateEntity;
  9. use Shopware\Core\Content\MailTemplate\Service\MailServiceInterface;
  10. use Shopware\Core\Content\Media\MediaService;
  11. use Shopware\Core\Framework\Context;
  12. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Exception\InconsistentCriteriaIdsException;
  14. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  15. use Shopware\Core\Framework\Event\BusinessEvent;
  16. use Shopware\Core\Framework\Event\EventData\EventDataType;
  17. use Shopware\Core\Framework\Event\MailActionInterface;
  18. use Shopware\Core\Framework\Validation\DataBag\DataBag;
  19. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  20. class MailSendSubscriber implements EventSubscriberInterface
  21. {
  22.     public const ACTION_NAME MailTemplateActions::MAIL_TEMPLATE_MAIL_SEND_ACTION;
  23.     public const MAIL_CONFIG_EXTENSION 'mail-attachments';
  24.     /**
  25.      * @var MailServiceInterface
  26.      */
  27.     private $mailService;
  28.     /**
  29.      * @var EntityRepositoryInterface
  30.      */
  31.     private $mailTemplateRepository;
  32.     /**
  33.      * @var MediaService
  34.      */
  35.     private $mediaService;
  36.     /**
  37.      * @var EntityRepositoryInterface
  38.      */
  39.     private $mediaRepository;
  40.     /**
  41.      * @var DocumentService
  42.      */
  43.     private $documentService;
  44.     /**
  45.      * @var EntityRepositoryInterface
  46.      */
  47.     private $documentRepository;
  48.     /**
  49.      * @var LoggerInterface
  50.      */
  51.     private $logger;
  52.     public function __construct(
  53.         MailServiceInterface $mailService,
  54.         EntityRepositoryInterface $mailTemplateRepository,
  55.         MediaService $mediaService,
  56.         EntityRepositoryInterface $mediaRepository,
  57.         EntityRepositoryInterface $documentRepository,
  58.         DocumentService $documentService,
  59.         LoggerInterface $logger
  60.     ) {
  61.         $this->mailService $mailService;
  62.         $this->mailTemplateRepository $mailTemplateRepository;
  63.         $this->mediaService $mediaService;
  64.         $this->mediaRepository $mediaRepository;
  65.         $this->documentRepository $documentRepository;
  66.         $this->documentService $documentService;
  67.         $this->logger $logger;
  68.     }
  69.     public static function getSubscribedEvents(): array
  70.     {
  71.         return [
  72.             self::ACTION_NAME => 'sendMail',
  73.         ];
  74.     }
  75.     /**
  76.      * @throws MailEventConfigurationException
  77.      * @throws SalesChannelNotFoundException
  78.      * @throws InconsistentCriteriaIdsException
  79.      */
  80.     public function sendMail(BusinessEvent $event): void
  81.     {
  82.         $mailEvent $event->getEvent();
  83.         $extension $event->getContext()->getExtension(self::MAIL_CONFIG_EXTENSION);
  84.         if (!$extension instanceof MailSendSubscriberConfig) {
  85.             $extension = new MailSendSubscriberConfig(false, [], []);
  86.         }
  87.         if ($extension->skip()) {
  88.             return;
  89.         }
  90.         if (!$mailEvent instanceof MailActionInterface) {
  91.             throw new MailEventConfigurationException('Not a instance of MailActionInterface', \get_class($mailEvent));
  92.         }
  93.         $config $event->getConfig();
  94.         if (!isset($config['mail_template_id'])) {
  95.             return;
  96.         }
  97.         $mailTemplate $this->getMailTemplate($config['mail_template_id'], $event->getContext());
  98.         if ($mailTemplate === null) {
  99.             return;
  100.         }
  101.         $data = new DataBag();
  102.         $recipients $mailEvent->getMailStruct()->getRecipients();
  103.         if (isset($config['recipients'])) {
  104.             $recipients $config['recipients'];
  105.         }
  106.         $data->set('recipients'$recipients);
  107.         $data->set('senderName'$mailTemplate->getTranslation('senderName'));
  108.         $data->set('salesChannelId'$mailEvent->getSalesChannelId());
  109.         $data->set('templateId'$mailTemplate->getId());
  110.         $data->set('customFields'$mailTemplate->getCustomFields());
  111.         $data->set('contentHtml'$mailTemplate->getTranslation('contentHtml'));
  112.         $data->set('contentPlain'$mailTemplate->getTranslation('contentPlain'));
  113.         $data->set('subject'$mailTemplate->getTranslation('subject'));
  114.         $data->set('mediaIds', []);
  115.         $attachments $this->buildAttachments($event$mailTemplate$extension);
  116.         if (!empty($attachments)) {
  117.             $data->set('binAttachments'$attachments);
  118.         }
  119.         try {
  120.             $this->mailService->send(
  121.                 $data->all(),
  122.                 $event->getContext(),
  123.                 $this->getTemplateData($mailEvent)
  124.             );
  125.             $writes array_map(static function ($id) {
  126.                 return ['id' => $id'sent' => true];
  127.             }, $extension->getDocumentIds());
  128.             if (!empty($writes)) {
  129.                 $this->documentRepository->update($writes$event->getContext());
  130.             }
  131.         } catch (\Exception $e) {
  132.             $this->logger->error(
  133.                 "Could not send mail:\n"
  134.                 $e->getMessage() . "\n"
  135.                 'Error Code:' $e->getCode() . "\n"
  136.                 "Template data: \n"
  137.                 json_encode($data->all()) . "\n"
  138.             );
  139.         }
  140.     }
  141.     private function getMailTemplate(string $idContext $context): ?MailTemplateEntity
  142.     {
  143.         $criteria = new Criteria([$id]);
  144.         $criteria->addAssociation('media.media');
  145.         $criteria->setLimit(1);
  146.         return $this->mailTemplateRepository
  147.             ->search($criteria$context)
  148.             ->first();
  149.     }
  150.     /**
  151.      * @throws MailEventConfigurationException
  152.      */
  153.     private function getTemplateData(MailActionInterface $event): array
  154.     {
  155.         $data = [];
  156.         /* @var EventDataType $item */
  157.         foreach (array_keys($event::getAvailableData()->toArray()) as $key) {
  158.             $getter 'get' ucfirst($key);
  159.             if (method_exists($event$getter)) {
  160.                 $data[$key] = $event->$getter();
  161.             } else {
  162.                 throw new MailEventConfigurationException('Data for ' $key ' not available.', \get_class($event));
  163.             }
  164.         }
  165.         return $data;
  166.     }
  167.     private function buildAttachments(BusinessEvent $eventMailTemplateEntity $mailTemplateMailSendSubscriberConfig $config): array
  168.     {
  169.         $attachments = [];
  170.         if ($mailTemplate->getMedia() !== null) {
  171.             foreach ($mailTemplate->getMedia() as $mailTemplateMedia) {
  172.                 if ($mailTemplateMedia->getMedia() === null) {
  173.                     continue;
  174.                 }
  175.                 if ($mailTemplateMedia->getLanguageId() !== null && $mailTemplateMedia->getLanguageId() !== $event->getContext()->getLanguageId()) {
  176.                     continue;
  177.                 }
  178.                 $attachments[] = $this->mediaService->getAttachment(
  179.                     $mailTemplateMedia->getMedia(),
  180.                     $event->getContext()
  181.                 );
  182.             }
  183.         }
  184.         if (!empty($config->getMediaIds())) {
  185.             $entities $this->mediaRepository->search(new Criteria($config->getMediaIds()), $event->getContext());
  186.             foreach ($entities as $media) {
  187.                 $attachments[] = $this->mediaService->getAttachment($media$event->getContext());
  188.             }
  189.         }
  190.         if (!empty($config->getDocumentIds())) {
  191.             $criteria = new Criteria($config->getDocumentIds());
  192.             $criteria->addAssociation('documentMediaFile');
  193.             $criteria->addAssociation('documentType');
  194.             $entities $this->documentRepository->search($criteria$event->getContext());
  195.             foreach ($entities as $document) {
  196.                 $document $this->documentService->getDocument($document$event->getContext());
  197.                 $attachments[] = [
  198.                     'content' => $document->getFileBlob(),
  199.                     'fileName' => $document->getFilename(),
  200.                     'mimeType' => $document->getContentType(),
  201.                 ];
  202.             }
  203.         }
  204.         return $attachments;
  205.     }
  206. }