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

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