You are here

MediaPdfThumbnailImageManager.php in Media PDF Thumbnail 8.4

File

src/Manager/MediaPdfThumbnailImageManager.php
View source
<?php

namespace Drupal\media_pdf_thumbnail\Manager;

use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\File\FileSystem;
use Drupal\file\FileInterface;
use Drupal\media\MediaInterface;

/**
 * Class MediaPdfThumbnailImageManager.
 *
 * @package Drupal\media_pdf_thumbnail\Manager
 */
class MediaPdfThumbnailImageManager {
  const VALID_MIME_TYPE = [
    'application/pdf',
  ];
  const GENERIC_FILENAME = 'generic.png';

  /**
   * MediaPdfThumbnailManager.
   *
   * @var \Drupal\media_pdf_thumbnail\Manager\MediaPdfThumbnailImagickManager
   */
  protected $mediaPdfThumbnailImagickManager;

  /**
   * EntityTypeManager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManager
   */
  protected $entityTypeManager;

  /**
   * FileSystem.
   *
   * @var \Drupal\Core\File\FileSystem
   */
  protected $fileSystem;

  /**
   * @var \Drupal\Core\Config\ConfigFactory
   */
  protected $configFactory;

  /**
   * @var \Drupal\Core\Database\Connection
   */
  protected $connection;

  /**
   * @var \Drupal\Core\Cache\Cache
   */
  protected $cache;

  /**
   * MediaPdfThumbnailImageManager constructor.
   *
   * @param \Drupal\media_pdf_thumbnail\Manager\MediaPdfThumbnailImagickManager $mediaPdfThumbnailImagickManager
   * @param \Drupal\Core\Entity\EntityTypeManager $entityTypeManager
   * @param \Drupal\Core\File\FileSystem $fileSystem
   * @param \Drupal\Core\Config\ConfigFactory $configFactory
   * @param \Drupal\Core\Database\Connection $connection
   * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache
   */
  public function __construct(MediaPdfThumbnailImagickManager $mediaPdfThumbnailImagickManager, EntityTypeManager $entityTypeManager, FileSystem $fileSystem, ConfigFactory $configFactory, Connection $connection, CacheTagsInvalidatorInterface $cache) {
    $this->mediaPdfThumbnailImagickManager = $mediaPdfThumbnailImagickManager;
    $this->entityTypeManager = $entityTypeManager;
    $this->fileSystem = $fileSystem;
    $this->configFactory = $configFactory;
    $this->connection = $connection;
    $this->cache = $cache;
  }

  /**
   * @param \Drupal\media\MediaInterface $media
   * @param $fieldName
   * @param $thumbnailType
   *
   * @return false
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Entity\EntityStorageException
   * @throws \Drupal\Core\TypedData\Exception\MissingDataException
   */
  public function createThumbnail(MediaInterface $media, $fieldName, $thumbnailType) {
    if (empty($media)) {
      return FALSE;
    }
    $entityTypeId = $media
      ->getEntityTypeId();
    if ($entityTypeId == 'media' && $fieldName) {
      if ($media
        ->hasField($fieldName) && !empty($media
        ->get($fieldName)
        ->getValue())) {
        $fileEntity = $this
          ->getFileEntity($media
          ->get($fieldName)
          ->getValue()[0]['target_id']);
        if ($fileEntity && in_array($fileEntity
          ->getMimeType(), self::VALID_MIME_TYPE)) {

          // Default thumbnail.
          $fileEntityInfo['fid'] = $this
            ->getGenericThumbnail();
          $fileEntityInfo['filename'] = NULL;
          if ($thumbnailType == 'pdf') {
            $fileEntityInfo = $this
              ->createThumbnailFileEntity($this
              ->generatePdfImage($fileEntity));
          }
          if (!empty($fileEntityInfo)) {
            $this
              ->setImageToMediaThumbnail($media, $fileEntityInfo, $thumbnailType);
          }
        }
      }
    }
  }

  /**
   * @param $fid
   *
   * @return \Drupal\Core\Entity\EntityInterface|null
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function getFileEntity($fid) {
    return $this->entityTypeManager
      ->getStorage('file')
      ->load($fid);
  }

  /**
   * @return int|string|null
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function getGenericThumbnail() {
    $uri = $this->configFactory
      ->get('media.settings')
      ->get('icon_base_uri');
    $files = $this->entityTypeManager
      ->getStorage('file')
      ->loadByProperties([
      'uri' => $uri . '/' . self::GENERIC_FILENAME,
    ]);
    return !empty($files) ? reset($files)
      ->id() : NULL;
  }

  /**
   * @param $fileUri
   *
   * @return array|void|null
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function createThumbnailFileEntity($fileUri) {
    if (empty($fileUri)) {
      return;
    }
    $infos = pathinfo($fileUri);
    $fileEntity = $this->entityTypeManager
      ->getStorage('file')
      ->create([
      'uri' => $fileUri,
      'status' => FILE_STATUS_PERMANENT,
    ]);
    $fileEntity
      ->save();
    return $fileEntity ? [
      'fid' => $fileEntity
        ->id(),
      'filename' => $infos['filename'],
    ] : NULL;
  }

  /**
   * @param \Drupal\file\FileInterface $fileEntity
   *
   * @return bool|string|null
   */
  protected function generatePdfImage(FileInterface $fileEntity) {
    $fileInfos = $this
      ->getFileInfos($fileEntity);
    if (!empty($fileInfos['source']) && !empty($fileInfos['destination'])) {
      return $this->mediaPdfThumbnailImagickManager
        ->generateImageFromPDF($fileInfos['source'], $fileInfos['destination']);
    }
    return NULL;
  }

  /**
   * @param \Drupal\file\FileInterface $fileEntity
   *
   * @return array
   */
  protected function getFileInfos(FileInterface $fileEntity) {
    $sourcePath = $fileEntity
      ->getFileUri();
    $destinationPath = $sourcePath . '.jpeg';
    return [
      'source' => $sourcePath,
      'destination' => $destinationPath,
    ];
  }

  /**
   * @param \Drupal\media\MediaInterface $media
   * @param $fileEntityInfo
   * @param $thumbnailType
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\TypedData\Exception\MissingDataException
   * @throws \Exception
   */
  protected function setImageToMediaThumbnail(MediaInterface $media, $fileEntityInfo, $thumbnailType) {
    $revisionFieldValue = $media
      ->get('vid')
      ->get(0)
      ->getValue();
    $vid = !empty($revisionFieldValue['value']) ? $revisionFieldValue['value'] : NULL;
    $mediaRevision = $this->entityTypeManager
      ->getStorage('media')
      ->loadRevision($vid);
    $currentThumbnailFileUri = $mediaRevision
      ->get('thumbnail')->entity
      ->getFileUri();
    $thumbnailFileUri = $this->entityTypeManager
      ->getStorage('file')
      ->load($fileEntityInfo['fid'])
      ->getFileUri();
    if ($currentThumbnailFileUri != $thumbnailFileUri) {
      $mediaRevision
        ->set('thumbnail', $fileEntityInfo['fid']);
      $mediaRevision
        ->save();
      $this->entityTypeManager
        ->getStorage($media
        ->getEntityTypeId())
        ->resetCache([
        $media
          ->id(),
      ]);
      $this->cache
        ->invalidateTags($media
        ->getCacheTagsToInvalidate());
    }
    return;

    // Manage revision.
    if ($vid) {

      // Handle file usage.
      $values = [
        'fid' => $fileEntityInfo['fid'],
        'module' => $media
          ->bundle(),
        'type' => $media
          ->getEntityTypeId(),
        'id' => $media
          ->id(),
      ];
      if (!$this
        ->entryExists('file_usage', $values)) {
        $query = $this->connection
          ->insert('file_usage');
        $values['count'] = 1;
        $query
          ->fields($values);
        $query
          ->execute();
      }

      // Handle media field revision.
      $query = $this->connection
        ->update('media_field_revision');
      $values = [
        'langcode' => $media
          ->language()
          ->getId(),
        'thumbnail__target_id' => $fileEntityInfo['fid'],
        'thumbnail__alt' => $fileEntityInfo['filename'],
      ];
      $query
        ->fields($values);
      $query
        ->condition('mid', $media
        ->id());
      $query
        ->condition('vid', $vid);
      $query
        ->condition('langcode', $media
        ->language()
        ->getId());
      $query
        ->execute();
      $this->entityTypeManager
        ->getStorage($media
        ->getEntityTypeId())
        ->resetCache([
        $media
          ->id(),
      ]);
      $this->cache
        ->invalidateTags($media
        ->getCacheTagsToInvalidate());
    }
  }

  /**
   * @param $table
   * @param $values
   *
   * @return bool
   */
  protected function entryExists($table, $values) {
    $query = $this->connection
      ->select($table, 't');
    foreach ($values as $key => $value) {
      $query
        ->condition('t.' . $key, $value);
    }
    $query
      ->fields('t', [
      'fid',
    ]);
    return !empty($query
      ->execute()
      ->fetchAssoc());
  }

}

Classes

Namesort descending Description
MediaPdfThumbnailImageManager Class MediaPdfThumbnailImageManager.