view_mode_crop-1.0.x-dev/src/StreamWrapper/CropStreamWrapper.php

src/StreamWrapper/CropStreamWrapper.php
<?php

namespace Drupal\view_mode_crop\StreamWrapper;

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\StreamWrapper\LocalStream;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\view_mode_crop\CropImageHelper;
use Drupal\view_mode_crop\Plugin\Field\FieldType\ViewModeCropImageItem;

/**
 * Crop stream wrapper.
 */
abstract class CropStreamWrapper extends LocalStream {

  /**
   * Create a derivate image for the given uri.
   *
   * @param string $uri
   *   The uri.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\TypedData\Exception\MissingDataException
   */
  protected function createDerivate(string $uri): void {
    // File does not exist, generate it.
    $target = StreamWrapperManager::getTarget($uri);

    $parsed = CropImageHelper::parsePathOrUri($target);

    if ($parsed === NULL) {
      return;
    }
    $storage = \Drupal::entityTypeManager()
      ->getStorage($parsed['entity_type_id']);

    $entity = $storage->load($parsed['entity_id']);

    if ($entity instanceof ContentEntityInterface && $entity->hasField($parsed['field_name'])) {
      $image_item = $entity->get($parsed['field_name'])->get($parsed['delta']);

      if ($image_item instanceof ViewModeCropImageItem) {
        CropImageHelper::getUri($image_item, $parsed['delta'], $parsed['view_mode']);
      }
    }
  }

  /**
   * {@inheritDoc}
   */
  public function url_stat($uri, $flags) { // phpcs:ignore
    $stat = parent::url_stat($uri, $flags);

    static $calls = [];

    foreach (array_keys($calls) as $call) {
      if (stripos($uri, $call) === 0) {
        return $stat;
      }
    }
    $calls[$uri] = $uri;

    if (!$stat) {
      $this->createDerivate($uri);
      $stat = parent::url_stat($uri, $flags);
    }

    unset($calls[$uri]);

    return $stat;
  }

}

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

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