You are here

MediaPdfThumbnailService.php in Media PDF Thumbnail 8.4

File

src/Service/MediaPdfThumbnailService.php
View source
<?php

namespace Drupal\media_pdf_thumbnail\Service;

use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\State\State;
use Drupal\media\MediaInterface;
use Drupal\media_pdf_thumbnail\Form\BundlesSettingsForm;
use Drupal\media_pdf_thumbnail\Manager\MediaPdfThumbnailQueueManager;

/**
 * Class MediaPdfThumbnailService
 *
 * @package Drupal\media_pdf_thumbnail\Service
 */
class MediaPdfThumbnailService {

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

  /**
   * @var \Drupal\media_pdf_thumbnail\Manager\MediaPdfThumbnailQueueManager
   */
  protected $mediaPdfThumbnailQueueManager;

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

  /**
   * @var \Drupal\Core\Config\Config|\Drupal\Core\Config\ImmutableConfig
   */
  protected $mediaPdfThumbnailConfig;

  /**
   * MediaPdfThumbnailService constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactory $configFactory
   * @param \Drupal\media_pdf_thumbnail\Manager\MediaPdfThumbnailQueueManager $mediaPdfThumbnailQueueManager
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   */
  public function __construct(ConfigFactory $configFactory, MediaPdfThumbnailQueueManager $mediaPdfThumbnailQueueManager, EntityTypeManagerInterface $entityTypeManager) {
    $this->configFactory = $configFactory;
    $this->mediaPdfThumbnailQueueManager = $mediaPdfThumbnailQueueManager;
    $this->entityTypeManager = $entityTypeManager;
    $this->mediaPdfThumbnailConfig = $configFactory
      ->get(BundlesSettingsForm::SETTINGS);
  }

  /**
   * Finish callback.
   *
   * @param mixed $success
   *   Success.
   * @param mixed $results
   *   Results.
   * @param mixed $operations
   *   Operations.
   */
  public static function finishedCallback($success, $results, $operations) {
    if ($success) {
      $message = \Drupal::translation()
        ->formatPlural(count($results), 'One task processed.', '@count tasks processed.');
      \Drupal::messenger()
        ->addMessage($message);
    }
    else {
      \Drupal::messenger()
        ->addError(t('Finished with an error.'));
    }
  }

  /**
   * @param \Drupal\media\MediaInterface $media
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function previousFileDelete(MediaInterface $media) {
    $new = $media
      ->isNew();
    $newRev = $media
      ->isNewRevision();
    $infos = $this
      ->getMediaBundleSettingsInfos($media);
    $fieldHasChanged = !empty($media->original) && !$media
      ->get($infos['field'])
      ->equals($media->original
      ->get($infos['field']));

    // Simple update with no new revision.
    if (!$new && !$newRev && $fieldHasChanged) {
      $thumbnailValue = $media->original
        ->get('thumbnail')
        ->getEntity()
        ->get('thumbnail')
        ->getValue();
      $fid = !empty($thumbnailValue[0]['target_id']) ? $thumbnailValue[0]['target_id'] : NULL;
      $this->entityTypeManager
        ->getStorage('file')
        ->load($fid)
        ->delete();
    }
  }

  /**
   * @param \Drupal\media\MediaInterface $entity
   *
   * @return array
   */
  protected function getMediaBundleSettingsInfos(MediaInterface $entity) {
    $bundle = $entity
      ->bundle();
    return [
      'enable' => $this->mediaPdfThumbnailConfig
        ->get($bundle . '_enable'),
      'field' => $this->mediaPdfThumbnailConfig
        ->get($bundle . '_field'),
    ];
  }

  /**
   * @param \Drupal\media\MediaInterface $media
   * @param $action
   *
   * @return null
   * @throws \Drupal\Core\TypedData\Exception\MissingDataException
   */
  public function handleEntity(MediaInterface $media, $action) {
    $infos = $this
      ->getMediaBundleSettingsInfos($media);
    $task = NULL;

    // Determine thumbnail type.
    $thumbnailType = $infos['enable'] ? 'pdf' : 'generic';

    // Determine task.
    switch ($action) {
      case 'create':
        $task = $thumbnailType == 'pdf' ? 'pdf' : NULL;
        break;
      case 'update':

        // If needs default thumbnail but it's not done.
        if ($thumbnailType == 'generic' && !$this
          ->hasDefaultThumbnail($media)) {
          $task = 'generic';
        }
        else {

          // If needs thumbnail from pdf.
          if ($thumbnailType == 'pdf') {

            // Default thumbnail must be changed.
            if (!$this
              ->hasDefaultThumbnail($media)) {
              $task = 'pdf';
            }
            else {

              // Thumbnail is already from pdf but the field's value has been updated. So needs regenerating a thumbnail.
              if (!$media
                ->get($infos['field'])
                ->equals($media->original
                ->get($infos['field']))) {
                $task = 'pdf';
              }
            }
          }
        }
    }
    if ($task === 'pdf') {
      self::generateThumbnail($media, $infos['field'], 'pdf', FALSE);
    }
    elseif ($task === 'generic') {
      self::generateThumbnail($media, $infos['field'], 'generic', FALSE);
    }
    return NULL;
  }

  /**
   * @param \Drupal\media\MediaInterface $media
   *
   * @return bool
   */
  protected function hasDefaultThumbnail(MediaInterface $media) {
    $file = $media
      ->get('thumbnail')->entity;
    $fileUri = $file ? $file
      ->getFileUri() : NULL;
    $genericThumbnailFileName = $media
      ->getSource()
      ->getPluginDefinition()['default_thumbnail_filename'];
    $genericFileUri = $this->configFactory
      ->get('media.settings')
      ->get('icon_base_uri') . '/' . $genericThumbnailFileName;
    return $fileUri == $genericFileUri;
  }

  /**
   * @param \Drupal\media\MediaInterface $media
   * @param $pdfFieldName
   * @param $thumbnailType
   * @param bool $byPassCron
   */
  public static function generateThumbnail(MediaInterface $media, $pdfFieldName, $thumbnailType, bool $byPassCron) {
    $mediaPdfThumbnailQueueManager = \Drupal::service('media_pdf_thumbnail.queue.manager');

    // Check if cron should be used.
    $cronEnable = !empty(\Drupal::configFactory()
      ->get(BundlesSettingsForm::SETTINGS)
      ->get('cron_enable'));
    $useCron = $byPassCron ? FALSE : $cronEnable;
    $mediaPdfThumbnailQueueManager
      ->createItem($media, $pdfFieldName, $thumbnailType, $useCron);
    $mediaPdfThumbnailQueueManager
      ->executeQueue();
  }

  /**
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function regenerateAllThumbnails() {
    $mediaStorage = $this->entityTypeManager
      ->getStorage('media');
    $operations = [];
    foreach ($mediaStorage
      ->loadMultiple() as $media) {
      $languageManager = \Drupal::service('language_manager');
      $languages = $languageManager
        ->getLanguages();
      foreach ($languages as $language) {
        $translation = $media
          ->hasTranslation($language
          ->getId()) ? $media
          ->getTranslation($language
          ->getId()) : NULL;
        if ($translation) {
          $translation
            ->bundle();
          $fieldName = $this->mediaPdfThumbnailConfig
            ->get($translation
            ->bundle() . '_field');
          $thumbnailType = $this->mediaPdfThumbnailConfig
            ->get($translation
            ->bundle() . '_enable') ? 'pdf' : 'generic';
          if (empty($fieldName) || empty($thumbnailType)) {
            continue;
          }
          $operations[] = [
            'Drupal\\media_pdf_thumbnail\\Service\\MediaPdfThumbnailService::generateThumbnail',
            [
              $translation,
              $fieldName,
              $thumbnailType,
              TRUE,
            ],
          ];
        }
      }
    }
    $batch = [
      'title' => t('Media PDF Thumbnail'),
      'operations' => $operations,
      'init_message' => t('Thumbnail creating process is starting.'),
      'progress_message' => t('Processed @current out of @total. Estimated time: @estimate.'),
      'error_message' => t('An error occurred during processing'),
      'finished' => '\\Drupal\\media_pdf_thumbnail\\Service\\MediaPdfThumbnailService::finishedCallback',
    ];
    batch_set($batch);
  }

}

Classes

Namesort descending Description
MediaPdfThumbnailService Class MediaPdfThumbnailService