postoffice-1.0.x-dev/extensions/postoffice_image/src/EventSubscriber/ImageEmbedSubscriber.php

extensions/postoffice_image/src/EventSubscriber/ImageEmbedSubscriber.php
<?php

namespace Drupal\postoffice_image\EventSubscriber;

use Drupal\image\Entity\ImageStyle;
use Drupal\image\ImageStyleInterface;
use Drupal\postoffice\Email\TemplateAttachmentsInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Mailer\Event\MessageEvent;
use Symfony\Component\Mime\Email;

/**
 * Embeds images supplied by the postoffice_image_embed twig filter.
 *
 * Runs with priority -50 (after Symfony MessageListener which is responsible
 * for body rendering).
 */
class ImageEmbedSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events = [];
    $events[MessageEvent::class] = ['onMessage', -50];
    return $events;
  }

  /**
   * Embeds images supplied by postoffice_image_embed twig filters.
   */
  public function onMessage(MessageEvent $event): void {
    $message = $event->getMessage();
    if ($message instanceof Email && $message instanceof TemplateAttachmentsInterface) {
      $settings = $message->getTemplateAttachments()->getSettings();
      $embeds = $settings['postofficeImageEmbeds'] ?? [];
      foreach ($embeds as $cid => ['uri' => $uri, 'style' => $style]) {
        if (!empty($style)) {
          $styleEntity = ImageStyle::load($style);
          $uri = $styleEntity ? $this->generateStyle($uri, $styleEntity) : NULL;
        }
        if (!empty($uri)) {
          $message->embedFromPath($uri, $cid);
        }
      }
    }
  }

  /**
   * Generates derivative and return URI for given image / style.
   */
  protected function generateStyle($imageUri, ImageStyleInterface $style): ?string {
    $derivativeUri = $style->buildUri($imageUri);

    if (!file_exists($derivativeUri)) {
      $style->createDerivative($imageUri, $derivativeUri);
    }

    return file_exists($derivativeUri) ? $derivativeUri : NULL;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc