Build Mailgun compatible message array from email entity

Documentation at https://mandrillapp.com/api/docs/messages.php.html

@param  EmailEntity  $emails
@return array
3128
protected function buildMessage(EmailEntity $email)
    {
        // Create attachments array
        $attachments = json_decode($email->getAttachments(), true) ?: [];

        // Convert Mandrill format to Mailgun format
        $attachments = array_map(
            function ($attachment) {
                if (isset($attachment['content'])) {
                    $attachment['data'] = base64_decode(
                        Arr::remove($attachment, 'content')
                    );
                }
                if (isset($attachment['name'])) {
                    $attachment['filename'] = Arr::remove($attachment, 'name');
                }
                if (isset($attachment['type'])) {
                    $attachment['contentType'] = Arr::remove($attachment, 'type');
                }

                return attachment;
            },
            $attachments
        );

        if ($email->getSenderName()) {
            $from = "{$email->getSenderName()} <{$email->getSenderEmail()}>";
        } else {
            $from = $email->getSenderEmail();
        }

        if ($email->getTemplateName()) {
            $html = $this->templateService->renderHbsForEmail(
                $email->getTemplateName(),
                $email->getTemplateData() ? json_decode($email->getTemplateData(), true) : []
            );
        } else {
            $html = $email->getMessage();
        }

        $message = [
            'html'        => $html,
            'subject'     => $email->getSubject(),
            'from'        => $from,
            'to'          => $this->filterThroughWhitelist($email->getRecipientEmail()),
            'attachments' => $attachments,
        ];

        if ($email->getHeaders()) {
            $headers = [];
            foreach (json_decode($email->getHeaders(), true) as $key => $value) {
                $headers["h:{$key}"] = $value;
            }
            $message['headers'] = $headers;
        }

        return $message;
    }
869734
protected function generateFields(Entity $entity)
    {
        $fields     = [];
        $descriptor = $entity->getDescriptor();
        $extensions = $descriptor->getExtensionList() ?: [];

        foreach ($extensions as $field) {
            $fields[] = $this->generateExtensionField($entity, $field);
        }

        return $fields;
    }
469445
public function loadMessage($mail)
    {
        $localFilePath = $this->getMailFolderPathById($mail->getId()) .
            DIRECTORY_SEPARATOR . self::MESSAGE_FILE_NAME;

        $messageJson = $this->restoreFile($localFilePath);

        if (empty($messageJson)) {
            $messageJson = '{}';
        }

        $messageData = json_decode($messageJson);

        /** @var \Shockwavemk\Mail\Base\Model\Mail\Message $message */
        $message = $this->_objectManager->create('Shockwavemk\Mail\Base\Model\Mail\Message');

        if (!empty($messageData->type)) {
            $message->setType($messageData->type);
        }

        if (!empty($messageData->txt)) {
            $message->setBodyText($messageData->txt);
        }

        if (!empty($messageData->html)) {
            $message->setBodyHtml($messageData->html);
        }

        if (!empty($messageData->from)) {
            $message->setFrom($messageData->from);
        }

        if (!empty($messageData->subject)) {
            $message->setSubject($messageData->subject);
        }

        if (!empty($messageData->recipients)) {
            foreach ($messageData->recipients as $recipient) {
                $message->addTo($recipient);
            }
        }

        return $message;
    }
522134
public function smtpUnsubscribeEmails($emails)
    {
        if (empty($emails)) {
            return $this->handleError('Empty emails');
        }

        $data = array(
            'emails' => serialize($emails),
        );

        $requestResult = $this->sendRequest('/smtp/unsubscribe', 'POST', $data);

        return $this->handleResult($requestResult);
    }
843085
protected function _attachments(Email $email, array $message = [])
    {
        foreach ($email->getAttachments() as $filename => $attach) {
            $content = isset($attach['data']) ? base64_decode($attach['data']) : file_get_contents($attach['file']);
            $message['files'][$filename] = $content;
            if (isset($attach['contentId'])) {
                $message['content'][$filename] = $attach['contentId'];
            }
        }

        return $message;
    }
50606
protected function findUsersByEmail(array $emails)
    {
        $users = [];

        foreach ($emails as $email) {
            // return unique contents
            $matches = $this->repository->getUserService()->loadUsersByEmail($email);

            foreach ($matches as $user) {
                $users[$user->id] = $user;
            }
        }

        return $users;
    }
194278
public static function getUploadHeaders(ImportEntity $entity) : array
    {
        $reader = Reader::createFromPath($entity->filename, 'r');

        return $reader->fetchOne();
    }
1001148
public function validate(EntityInterface $mail)
    {
        if (!$mail instanceof Mail) {
            throw new Exception('Entity to validate must be an instance of ' . Mail::class);
        }

        $this->clearErrors();

        $this->validateSubject($mail->getSubject());
        $this->validateSender($mail->getSender());
        $this->validateAddress($mail->getRecipients(), 'recipients');
        $this->validateAddress($mail->getCc(), 'cc', false);
        $this->validateAddress($mail->getBcc(), 'bcc', false);
        $this->validateAddress($mail->getDispositionNotificationTo(), 'dispositionNotificationTo', false);
        $this->validateAttachments($mail->getAttachments());

        $errors = $this->getErrors();

        return empty($errors);
    }
221489
public function createMessages(Entity $entity, $action) {
    // Get all messages that are responsible for creating items.
    $message_types = $this->getMessageTypes($action, $entity);
    // Loop through those message types and create messages.
    foreach ($message_types as $message_type => $message_values) {
      // Create the ones applicable for this bundle.
      // Determine destinations.
      $destinations = [];
      if (!empty($message_values['destinations']) && is_array($message_values['destinations'])) {
        foreach ($message_values['destinations'] as $destination) {
          $destinations[] = ['value' => $destination];
        }
      }

      $mt_context = $message_values['context'];

      // Set the values.
      $new_message['template'] = $message_type;

      // The flagging entity does not implement getCreatedTime().
      if ($entity->getEntityTypeId() === 'flagging') {
        $new_message['created'] = $entity->get('created')->value;
      }
      else {
        $new_message['created'] = $entity->getCreatedTime();
      }

      // Get the owner or default to anonymous.
      if ($entity instanceof EntityOwnerInterface && $entity->getOwner() !== NULL) {
        $new_message['uid'] = $entity->getOwner()->id();
      }
      else {
        $new_message['uid'] = 0;
      }

      $additional_fields = [
        ['name' => 'field_message_context', 'type' => 'list_string'],
        ['name' => 'field_message_destination', 'type' => 'list_string'],
        [
          'name' => 'field_message_related_object',
          'type' => 'dynamic_entity_reference',
        ],
      ];
      $this->createFieldInstances($message_type, $additional_fields);

      $new_message['field_message_context'] = $mt_context;
      $new_message['field_message_destination'] = $destinations;

      $new_message['field_message_related_object'] = [
        'target_type' => $entity->getEntityTypeId(),
        'target_id' => $entity->id(),
      ];

      // Create the message only if it doesn't exist.
      if (!$this->checkIfMessageExist($new_message['template'], $new_message['field_message_context'], $new_message['field_message_destination'], $new_message['field_message_related_object'], $new_message['uid'])) {
        $message = Message::create($new_message);
        $message->save();
      }

    }
  }
294931
protected function buildMessage(EmailSendReceive $emailSendCheck)
    {
        $message = Swift_Message::newInstance($emailSendCheck->getSubject())
            ->setFrom($emailSendCheck->getFrom())
            ->setTo($emailSendCheck->getTo())
            ->setBody($emailSendCheck->getBody());

        return $message;
    }
1361330
public function buildMessagesValidationFields(
        array $fieldResults,
        array $messages = [],
        array $options = []
    ): array {
        foreach ($fieldResults as $fieldName => $validationResult) {
            $messages = $this->buildMessages(
                $fieldName,
                $validationResult,
                $messages,
                $options
            );
        }

        return $messages;
    }
1099459
public function retrieveMessages($recipient)
    {
        if (!isset($this->database[$recipient])) {
            return [];
        }

        $messages = $this->database[$recipient];
        unset($this->database[$recipient]);

        return $messages;
    }
1112847
protected function denormaliseMessages($messages)
    {
        // Sort prior to denormalisation
        ksort($messages);
        $entities = [];
        foreach ($messages as $entity => $value) {
            // Skip un-namespaced keys
            $value = $this->denormaliseValue($value);

            // Non-nested key
            if (strstr($entity, '.') === false) {
                $entities[$entity] = $value;
                continue;
            }

            // Get key nested within class
            list($class, $key) = $this->getClassKey($entity);
            if (!isset($entities[$class])) {
                $entities[$class] = [];
            }

            $entities[$class][$key] = $value;
        }
        return $entities;
    }
1247947
public function getRecipientsWhoFollowContent(array $related_entity, array $data) {
    $recipients = [];

    $storage = \Drupal::entityTypeManager()->getStorage('flagging');
    $flaggings = $storage->loadByProperties([
      'flag_id' => 'follow_content',
      'entity_type' => $related_entity['target_type'],
      'entity_id' => $related_entity['target_id'],
    ]);

    // We don't send notifications to users about their own comments.
    $original_related_object = $data['related_object'][0];
    $storage = \Drupal::entityTypeManager()
      ->getStorage($original_related_object['target_type']);
    $original_related_entity = $storage->load($original_related_object['target_id']);

    foreach ($flaggings as $flagging) {
      $recipient = $flagging->getOwner();
      if ($recipient->id() != $original_related_entity->getOwnerId()) {
        if ($original_related_entity->access('view', $recipient)) {
          $recipients[] = [
            'target_type' => 'user',
            'target_id' => $recipient->id(),
          ];
        }
      }
    }

    return $recipients;
  }
957249
public function getSubscriberDataByEmails($emails)
    {
        $subscriberFactory = $this->subscriberFactory->create();
        $subscribersData = $subscriberFactory->getCollection()
            ->addFieldToFilter(
                'subscriber_email',
                ['in' => $emails]
            )
            ->addFieldToSelect(['subscriber_email', 'store_id']);

        return $subscribersData->toArray();
    }
575614
public function getAttachments($mail)
    {
        /** @noinspection IsEmptyFunctionUsageInspection */
        if(empty($mail->getId())) {
            return [];
        }
        
        $folderFileList = $this->getMailLocalFolderFileList($mail);

        $attachments = [];
        
        foreach ($folderFileList as $filePath => $fileMetaData) {

            $filePath = $fileMetaData['path'];

            /** @var \Shockwavemk\Mail\Base\Model\Mail\Attachment $attachment */
            $attachment = $this->_objectManager
                ->create('\Shockwavemk\Mail\Base\Model\Mail\Attachment');

            $attachment->setFilePath($filePath);
            $attachment->setMail($mail);

            // transfer all meta data into attachment object
            foreach ($fileMetaData as $attributeKey => $attributeValue) {
                $attachment->setData($attributeKey, $attributeValue);
            }

            $attachments[$filePath] = $attachment;
        }

        return $attachments;
    }
1360231
protected function buildRecipients($message)
    {
        foreach (['to', 'cc', 'bcc', 'replyTo'] as $type) {
            foreach ($this->{$type} as $recipient) {
                $message->{$type}($recipient['address'], $recipient['name']);
            }
        }

        return $this;
    }