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

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\Mail\Service\AbstractMailService;
  6. use Shopware\Core\Content\MailTemplate\Event\MailSendSubscriberBridgeEvent;
  7. use Shopware\Core\Content\MailTemplate\Exception\MailEventConfigurationException;
  8. use Shopware\Core\Content\MailTemplate\Exception\SalesChannelNotFoundException;
  9. use Shopware\Core\Content\MailTemplate\MailTemplateActions;
  10. use Shopware\Core\Content\MailTemplate\MailTemplateEntity;
  11. use Shopware\Core\Content\Media\MediaService;
  12. use Shopware\Core\Framework\Adapter\Translation\Translator;
  13. use Shopware\Core\Framework\Context;
  14. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  15. use Shopware\Core\Framework\DataAbstractionLayer\Exception\InconsistentCriteriaIdsException;
  16. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  17. use Shopware\Core\Framework\Event\BusinessEvent;
  18. use Shopware\Core\Framework\Event\MailActionInterface;
  19. use Shopware\Core\Framework\Feature;
  20. use Shopware\Core\Framework\Validation\DataBag\DataBag;
  21. use Shopware\Core\System\Locale\LanguageLocaleCodeProvider;
  22. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  23. use Symfony\Contracts\EventDispatcher\Event;
  24. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  25. /**
  26.  * @deprecated tag:v6.5.0 - reason:remove-subscriber - Will be removed in v6.5.0 Use SendMailAction instead
  27.  */
  28. class MailSendSubscriber implements EventSubscriberInterface
  29. {
  30.     public const ACTION_NAME MailTemplateActions::MAIL_TEMPLATE_MAIL_SEND_ACTION;
  31.     public const MAIL_CONFIG_EXTENSION 'mail-attachments';
  32.     private EntityRepositoryInterface $mailTemplateRepository;
  33.     private MediaService $mediaService;
  34.     private EntityRepositoryInterface $mediaRepository;
  35.     private DocumentService $documentService;
  36.     private EntityRepositoryInterface $documentRepository;
  37.     private LoggerInterface $logger;
  38.     private AbstractMailService $emailService;
  39.     private EventDispatcherInterface $eventDispatcher;
  40.     private EntityRepositoryInterface $mailTemplateTypeRepository;
  41.     private Translator $translator;
  42.     private LanguageLocaleCodeProvider $languageLocaleProvider;
  43.     /**
  44.      * @internal
  45.      */
  46.     public function __construct(
  47.         AbstractMailService $emailService,
  48.         EntityRepositoryInterface $mailTemplateRepository,
  49.         MediaService $mediaService,
  50.         EntityRepositoryInterface $mediaRepository,
  51.         EntityRepositoryInterface $documentRepository,
  52.         DocumentService $documentService,
  53.         LoggerInterface $logger,
  54.         EventDispatcherInterface $eventDispatcher,
  55.         EntityRepositoryInterface $mailTemplateTypeRepository,
  56.         Translator $translator,
  57.         LanguageLocaleCodeProvider $languageLocaleProvider
  58.     ) {
  59.         $this->mailTemplateRepository $mailTemplateRepository;
  60.         $this->mediaService $mediaService;
  61.         $this->mediaRepository $mediaRepository;
  62.         $this->documentRepository $documentRepository;
  63.         $this->documentService $documentService;
  64.         $this->logger $logger;
  65.         $this->emailService $emailService;
  66.         $this->eventDispatcher $eventDispatcher;
  67.         $this->mailTemplateTypeRepository $mailTemplateTypeRepository;
  68.         $this->translator $translator;
  69.         $this->languageLocaleProvider $languageLocaleProvider;
  70.     }
  71.     public static function getSubscribedEvents(): array
  72.     {
  73.         return [
  74.             self::ACTION_NAME => 'sendMail',
  75.         ];
  76.     }
  77.     /**
  78.      * @throws MailEventConfigurationException
  79.      * @throws SalesChannelNotFoundException
  80.      * @throws InconsistentCriteriaIdsException
  81.      */
  82.     public function sendMail(Event $event): void
  83.     {
  84.         if (Feature::isActive('FEATURE_NEXT_17858')) {
  85.             return;
  86.         }
  87.         if (!$event instanceof BusinessEvent) {
  88.             return;
  89.         }
  90.         $mailEvent $event->getEvent();
  91.         $extension $event->getContext()->getExtension(self::MAIL_CONFIG_EXTENSION);
  92.         if (!$extension instanceof MailSendSubscriberConfig) {
  93.             $extension = new MailSendSubscriberConfig(false, [], []);
  94.         }
  95.         if ($extension->skip()) {
  96.             return;
  97.         }
  98.         if (!$mailEvent instanceof MailActionInterface) {
  99.             throw new MailEventConfigurationException('Not a instance of MailActionInterface', \get_class($mailEvent));
  100.         }
  101.         $config $event->getConfig();
  102.         if (!isset($config['mail_template_id'])) {
  103.             return;
  104.         }
  105.         $mailTemplate $this->getMailTemplate($config['mail_template_id'], $event->getContext());
  106.         if ($mailTemplate === null) {
  107.             return;
  108.         }
  109.         $injectedTranslator $this->injectTranslator($mailEvent);
  110.         $data = new DataBag();
  111.         $recipients $mailEvent->getMailStruct()->getRecipients();
  112.         if (isset($config['recipients']) && !empty($config['recipients'])) {
  113.             $recipients $config['recipients'];
  114.         }
  115.         $data->set('recipients'$recipients);
  116.         $data->set('senderName'$mailTemplate->getTranslation('senderName'));
  117.         $data->set('salesChannelId'$mailEvent->getSalesChannelId());
  118.         $data->set('templateId'$mailTemplate->getId());
  119.         $data->set('customFields'$mailTemplate->getCustomFields());
  120.         $data->set('contentHtml'$mailTemplate->getTranslation('contentHtml'));
  121.         $data->set('contentPlain'$mailTemplate->getTranslation('contentPlain'));
  122.         $data->set('subject'$mailTemplate->getTranslation('subject'));
  123.         $data->set('mediaIds', []);
  124.         $attachments $this->buildAttachments($event$mailTemplate$extension);
  125.         if (!empty($attachments)) {
  126.             $data->set('binAttachments'$attachments);
  127.         }
  128.         $this->eventDispatcher->dispatch(new MailSendSubscriberBridgeEvent($data$mailTemplate$event));
  129.         if ($data->has('templateId')) {
  130.             try {
  131.                 $this->mailTemplateTypeRepository->update([[
  132.                     'id' => $mailTemplate->getMailTemplateTypeId(),
  133.                     'templateData' => $this->getTemplateData($mailEvent),
  134.                 ]], $mailEvent->getContext());
  135.             } catch (\Throwable $e) {
  136.                 // Dont throw errors if this fails // Fix with NEXT-15475
  137.             }
  138.         }
  139.         try {
  140.             $this->emailService->send(
  141.                 $data->all(),
  142.                 $event->getContext(),
  143.                 $this->getTemplateData($mailEvent)
  144.             );
  145.             $writes array_map(static function ($id) {
  146.                 return ['id' => $id'sent' => true];
  147.             }, $extension->getDocumentIds());
  148.             if (!empty($writes)) {
  149.                 $this->documentRepository->update($writes$event->getContext());
  150.             }
  151.         } catch (\Exception $e) {
  152.             $this->logger->error(
  153.                 "Could not send mail:\n"
  154.                 $e->getMessage() . "\n"
  155.                 'Error Code:' $e->getCode() . "\n"
  156.                 "Template data: \n"
  157.                 json_encode($data->all()) . "\n"
  158.             );
  159.         }
  160.         if ($injectedTranslator) {
  161.             $this->translator->resetInjection();
  162.         }
  163.     }
  164.     private function getMailTemplate(string $idContext $context): ?MailTemplateEntity
  165.     {
  166.         $criteria = new Criteria([$id]);
  167.         $criteria->addAssociation('media.media');
  168.         $criteria->setLimit(1);
  169.         return $this->mailTemplateRepository
  170.             ->search($criteria$context)
  171.             ->first();
  172.     }
  173.     /**
  174.      * @throws MailEventConfigurationException
  175.      */
  176.     private function getTemplateData(MailActionInterface $event): array
  177.     {
  178.         $data = [];
  179.         foreach (array_keys($event::getAvailableData()->toArray()) as $key) {
  180.             $getter 'get' ucfirst($key);
  181.             if (method_exists($event$getter)) {
  182.                 $data[$key] = $event->$getter();
  183.             } else {
  184.                 throw new MailEventConfigurationException('Data for ' $key ' not available.', \get_class($event));
  185.             }
  186.         }
  187.         return $data;
  188.     }
  189.     private function buildAttachments(BusinessEvent $eventMailTemplateEntity $mailTemplateMailSendSubscriberConfig $config): array
  190.     {
  191.         $attachments = [];
  192.         if ($mailTemplate->getMedia() !== null) {
  193.             foreach ($mailTemplate->getMedia() as $mailTemplateMedia) {
  194.                 if ($mailTemplateMedia->getMedia() === null) {
  195.                     continue;
  196.                 }
  197.                 if ($mailTemplateMedia->getLanguageId() !== null && $mailTemplateMedia->getLanguageId() !== $event->getContext()->getLanguageId()) {
  198.                     continue;
  199.                 }
  200.                 $attachments[] = $this->mediaService->getAttachment(
  201.                     $mailTemplateMedia->getMedia(),
  202.                     $event->getContext()
  203.                 );
  204.             }
  205.         }
  206.         if (!empty($config->getMediaIds())) {
  207.             $entities $this->mediaRepository->search(new Criteria($config->getMediaIds()), $event->getContext());
  208.             foreach ($entities as $media) {
  209.                 $attachments[] = $this->mediaService->getAttachment($media$event->getContext());
  210.             }
  211.         }
  212.         if (!empty($config->getDocumentIds())) {
  213.             $criteria = new Criteria($config->getDocumentIds());
  214.             $criteria->addAssociation('documentMediaFile');
  215.             $criteria->addAssociation('documentType');
  216.             $entities $this->documentRepository->search($criteria$event->getContext());
  217.             foreach ($entities as $document) {
  218.                 $document $this->documentService->getDocument($document$event->getContext());
  219.                 $attachments[] = [
  220.                     'content' => $document->getFileBlob(),
  221.                     'fileName' => $document->getFilename(),
  222.                     'mimeType' => $document->getContentType(),
  223.                 ];
  224.             }
  225.         }
  226.         return $attachments;
  227.     }
  228.     private function injectTranslator(MailActionInterface $event): bool
  229.     {
  230.         if ($event->getSalesChannelId() === null) {
  231.             return false;
  232.         }
  233.         if ($this->translator->getSnippetSetId() !== null) {
  234.             return false;
  235.         }
  236.         $this->translator->injectSettings(
  237.             $event->getSalesChannelId(),
  238.             $event->getContext()->getLanguageId(),
  239.             $this->languageLocaleProvider->getLocaleForLanguageId($event->getContext()->getLanguageId()),
  240.             $event->getContext()
  241.         );
  242.         return true;
  243.     }
  244. }