inline_image_saver-1.0.x-dev/src/MimeType/InlineImageFileBinaryMimeResolver.php

src/MimeType/InlineImageFileBinaryMimeResolver.php
<?php

declare(strict_types=1);

namespace Drupal\inline_image_saver\MimeType;

use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Symfony\Component\Mime\FileBinaryMimeTypeGuesser;
use Symfony\Component\Mime\MimeTypeGuesserInterface;

/**
 * Provides an image MIME type resolver using the 'file' command.
 */
class InlineImageFileBinaryMimeResolver extends InlineImageMimeResolverBase {

  public function __construct(protected readonly FileSystemInterface $fileSystem) {}

  /**
   * A binary MIME type guesser.
   */
  protected MimeTypeGuesserInterface $binaryGuesser;

  /**
   * {@inheritdoc}
   */
  public function isSupported(?TranslatableMarkup &$reason = NULL): bool {
    $reason = NULL;
    if ($this->getBinaryGuesser()->isGuesserSupported()) {
      return TRUE;
    }
    $reason = $this->t('The "<code>file</code>" command is not available in the current environment.');
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  protected function doResolveByUri(string $uri): ?string {
    if (!$path = $this->fileSystem->realpath($uri)) {
      if (!is_readable($uri)) {
        throw new \InvalidArgumentException("Failed to resolve URI: $uri");
      }
      return $this->doResolveByData(file_get_contents($uri));
    }
    return $this->getBinaryGuesser()->guessMimeType($path);
  }

  /**
   * {@inheritdoc}
   */
  protected function doResolveByData(string $data): ?string {
    if (!$path = $this->fileSystem->tempnam('temporary://', 'ii_')) {
      throw new \RuntimeException('Failed to create a temporary file name');
    }
    $uri = $this->fileSystem->saveData($data, $path);
    if (!$path = $this->fileSystem->realpath($uri)) {
      throw new \InvalidArgumentException("Failed to resolve URI: $uri");
    }
    return $this->getBinaryGuesser()->guessMimeType($path);
  }

  /**
   * Returns the binary MIME type guesser.
   *
   * @return \Symfony\Component\Mime\MimeTypeGuesserInterface
   *   The binary MIME type guesser.
   */
  protected function getBinaryGuesser(): MimeTypeGuesserInterface {
    return $this->binaryGuesser ??= new FileBinaryMimeTypeGuesser();
  }

}

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

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