You are here

public function EmailAttachmentEvaluator::evaluateAttachments in Easy Email 8

Same name and namespace in other branches
  1. 2.0.x src/Service/EmailAttachmentEvaluator.php \Drupal\easy_email\Service\EmailAttachmentEvaluator::evaluateAttachments()

@inheritDoc

Overrides EmailAttachmentEvaluatorInterface::evaluateAttachments

File

src/Service/EmailAttachmentEvaluator.php, line 48

Class

EmailAttachmentEvaluator

Namespace

Drupal\easy_email\Service

Code

public function evaluateAttachments(EasyEmailInterface $email, $save_attachments_to = FALSE) {
  $this->eventDispatcher
    ->dispatch(EasyEmailEvents::EMAIL_PREATTACHMENTEVAL, new EasyEmailEvent($email));
  $files = $email
    ->getEvaluatedAttachments();

  // If save attachments has been enabled, check for any programmatically added files and save them.
  if (!empty($save_attachments_to) && !empty($files)) {
    foreach ($files as $i => $file) {
      $this
        ->saveAttachment($email, $file->uri, $save_attachments_to);
      unset($files[$i]);

      // This will get re-added in the direct files below.
    }
  }

  // Files attached directly to email entity
  if ($email
    ->hasField('attachment')) {
    $attachments = $email
      ->getAttachments();
    if (!empty($attachments)) {
      foreach ($attachments as $attachment) {
        $file = new \stdClass();
        $file->uri = $attachment
          ->getFileUri();
        $file->filename = $attachment
          ->getFilename();
        $file->filemime = $attachment
          ->getMimeType();
        $files[] = $file;
      }
    }
  }

  // Dynamic Attachments
  if ($email
    ->hasField('attachment_path')) {
    $attachment_paths = $email
      ->getAttachmentPaths();
    if (!empty($attachment_paths)) {
      foreach ($attachment_paths as $path) {

        // Relative paths that start with '/' get messed up by the realpath call below.
        if (strpos($path, '/') === 0) {
          $path = substr($path, 1);
        }
        $realpath = $this->fileSystem
          ->realpath($path);
        if (!file_exists($realpath)) {
          continue;
        }
        if (!empty($save_attachments_to) && $email
          ->hasField('attachment')) {
          $this
            ->saveAttachment($email, $realpath, $save_attachments_to);
        }
        $file = new \stdClass();
        $file->uri = $path;
        $file->filename = $this->fileSystem
          ->basename($path);
        $file->filemime = $this->mimeTypeGuesser
          ->guess($path);
        $files[] = $file;
      }
    }
  }
  $email
    ->setEvaluatedAttachments($files);
  $this->eventDispatcher
    ->dispatch(EasyEmailEvents::EMAIL_ATTACHMENTEVAL, new EasyEmailEvent($email));
}