postoffice-1.0.x-dev/extensions/postoffice_image/src/Template/TwigExtension.php

extensions/postoffice_image/src/Template/TwigExtension.php
<?php

namespace Drupal\postoffice_image\Template;

use Drupal\Core\Render\RendererInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

/**
 * A class providing postoffice Twig extensions.
 */
class TwigExtension extends AbstractExtension {

  /**
   * The renderer.
   */
  protected RendererInterface $renderer;

  /**
   * Constructs postoffice twig extension.
   *
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
   */
  public function __construct(RendererInterface $renderer) {
    $this->renderer = $renderer;
  }

  /**
   * {@inheritdoc}
   */
  public function getFunctions(): array {
    return [
      new TwigFunction('postoffice_image_embed', $this->embedImage(...)),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getFilters(): array {
    return [
      new TwigFilter('postoffice_image_embed', $this->embedImage(...)),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getName(): string {
    return 'postoffice_image';
  }

  /**
   * Embeds an image specified by its uri, optionally applies an image style.
   *
   * Returns the cid (MIME Content-ID).
   *
   * Allows Twig templates to embed an image using a filter
   * @code
   * {% <img src="cid:{{ postoffice_image_embed('path/to/some/file.jpg') }}"> %}
   * {% <img src="cid:{{ postoffice_image_embed(imageUri, 'email') }}"> %}
   * @endcode
   * Or a filter
   * @code
   * {% <img src="cid:{{ 'path/to/some/file.jpg'|postoffice_image_embed }}"> %}
   * {% <img src="cid:{{ imageUri|postoffice_image_embed('email') }}"> %}
   * @endcode
   */
  public function embedImage(string $uri, ?string $style = NULL, ?string $cid = NULL): string {
    if (!isset($cid)) {
      $cid = $this->generateContentId();
    }

    $templateAttached['#attached']['drupalSettings']['postofficeImageEmbeds'][$cid] = [
      'uri' => $uri,
      'style' => $style,
    ];
    $this->renderer->render($templateAttached);

    return $cid;
  }

  /**
   * Generates a MIME Content-ID.
   */
  protected function generateContentId(): string {
    return bin2hex(random_bytes(16)) . '@postoffice';
  }

}

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

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