You are here

class DemoImage in Panopoly 8.2

Process plugin for creating demo images from files in the module.

Plugin annotation


@MigrateProcessPlugin(
  id = "panopoly_demo_image"
)

Hierarchy

Expanded class hierarchy of DemoImage

1 file declares its use of DemoImage
DemoImageTest.php in modules/panopoly/panopoly_core/tests/src/Unit/Plugin/migrate/process/DemoImageTest.php

File

modules/panopoly/panopoly_core/src/Plugin/migrate/process/DemoImage.php, line 24

Namespace

Drupal\panopoly_core\Plugin\migrate\process
View source
class DemoImage extends ProcessPluginBase implements ContainerFactoryPluginInterface {

  /**
   * The migration plugin.
   *
   * @var \Drupal\migrate\Plugin\MigrationInterface
   */
  protected $migration;

  /**
   * The file entity storage.
   *
   * @var \Drupal\file\FileStorageInterface
   */
  protected $fileStorage;

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The filesystem.
   *
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $filesystem;

  /**
   * The image factory.
   *
   * @var \Drupal\Core\Image\ImageFactory
   */
  protected $imageFactory;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, FileStorageInterface $file_storage, ModuleHandlerInterface $module_handler, FileSystemInterface $filesystem, ImageFactory $image_factory) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->migration = $migration;
    $this->fileStorage = $file_storage;
    $this->moduleHandler = $module_handler;
    $this->filesystem = $filesystem;
    $this->imageFactory = $image_factory;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
    return new static($configuration, $plugin_id, $plugin_definition, $migration, $container
      ->get('entity_type.manager')
      ->getStorage('file'), $container
      ->get('module_handler'), $container
      ->get('file_system'), $container
      ->get('image.factory'));
  }

  /**
   * Removes trailing characters from given path.
   *
   * @param string $path
   *   The path to process.
   *
   * @return string
   *   The path without any trailing slashes.
   */
  protected function removeTrailing($path) {
    return rtrim($path, '/ ');
  }

  /**
   * Gets the source path (within the module providing the migration).
   *
   * @return string
   *   The path relative to the Drupal root.
   */
  protected function getSourcePath() {
    $module_path = $this->moduleHandler
      ->getModule($this->migration
      ->getPluginDefinition()['provider'])
      ->getPath();
    $relative_path = !empty($this->configuration['source_path']) ? $this->configuration['source_path'] : 'import/images';
    return $this
      ->removeTrailing($module_path . '/' . $relative_path);
  }

  /**
   * Gets the destination path.
   *
   * @return string
   *   The destination path (using a stream wrapper).
   */
  protected function getDestinationPath() {
    if (!empty($this->configuration['destination_path'])) {
      return $this
        ->removeTrailing($this->configuration['destination_path']);
    }
    return 'public://demo';
  }

  /**
   * Gets an existing file entity if there is one.
   *
   * @param string $uri
   *   The file URI (path).
   *
   * @return \Drupal\file\FileInterface|null
   *   The file or NULL.
   */
  protected function findExistingFile($uri) {
    $files = $this->fileStorage
      ->loadByProperties([
      'uri' => $uri,
    ]);
    if (!empty($files)) {
      return reset($files);
    }
    return NULL;
  }

  /**
   * Copy the file.
   *
   * @param string $source_path
   *   The source path.
   * @param string $destination_path
   *   The destination path.
   *
   * @return bool
   *   TRUE if successful; otherwise FALSE.
   */
  protected function copyFile($source_path, $destination_path) {
    $dir = $this->filesystem
      ->dirname($destination_path);

    // Apparently, file_prepare_directory() can't deal with a protocol but no
    // path, so we convert it to the real path.
    if (substr($dir, -3) == '://') {
      $dir = $this->filesystem
        ->realpath($dir);
    }
    if ($this->filesystem
      ->prepareDirectory($dir, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS)) {
      return @copy($source_path, $destination_path);
    }
    return FALSE;
  }

  /**
   * Creates a new file from the source path.
   *
   * @param string $source_path
   *   The source path.
   * @param string $destination_path
   *   The destination path.
   *
   * @return \Drupal\file\FileInterface
   *   The file that was created
   *
   * @throws \Drupal\migrate\MigrateException
   */
  protected function createFile($source_path, $destination_path) {
    if (!$this
      ->copyFile($source_path, $destination_path)) {
      throw new MigrateException("Unable to copy {$source_path} to {$destination_path}");
    }
    $file = $this->fileStorage
      ->create([
      'uri' => $destination_path,
      'status' => TRUE,
    ]);
    $file
      ->save();
    return $file;
  }

  /**
   * Finds existing or creates a new file.
   *
   * @param string $source_path
   *   The source path.
   * @param string $destination_path
   *   The destination path.
   *
   * @return \Drupal\file\FileInterface
   *   The file that was found or created.
   *
   * @throws \Drupal\migrate\MigrateException
   */
  protected function findOrCreateFile($source_path, $destination_path) {
    $file = $this
      ->findExistingFile($destination_path);
    if (!$file) {
      $file = $this
        ->createFile($source_path, $destination_path);
    }
    return $file;
  }

  /**
   * Checks that a file exists and is readable.
   *
   * We're wrapping the filesystem so it's easier to test ::transform().
   *
   * @param string $path
   *   The path.
   *
   * @return bool
   *   TRUE if the file is good; FALSE otherwise.
   */
  protected function checkFile($path) {
    return file_exists($path);
  }

  /**
   * Gets the value of an optional property.
   *
   * @param string $config_name
   *   The configuration key that holds the name of the source property.
   * @param \Drupal\migrate\Row $row
   *   The row.
   *
   * @return mixed|null
   *   Returns the value of the property or NULL if not found.
   */
  protected function getOptionalProperty($config_name, Row $row) {
    if (!empty($this->configuration[$config_name])) {
      return $row
        ->getSourceProperty($this->configuration[$config_name]);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    // The only required property is the filename property.
    if (empty($this->configuration['filename_property'])) {
      return [];
    }
    $filename = $row
      ->getSourceProperty($this->configuration['filename_property']);
    $destination_path = $this
      ->getDestinationPath() . '/' . $filename;
    $source_path = $this
      ->getSourcePath() . '/' . $filename;
    if (!$this
      ->checkFile($source_path)) {
      throw new MigrateException('Cannot find source image: ' . $source_path);
    }
    $file = $this
      ->findOrCreateFile($source_path, $destination_path);
    $image = $this->imageFactory
      ->get($destination_path);
    return [
      'target_id' => $file
        ->id(),
      'display' => 1,
      'description' => $this
        ->getOptionalProperty('description_property', $row) ?: '',
      'alt' => $this
        ->getOptionalProperty('alt_property', $row) ?: '',
      'title' => $this
        ->getOptionalProperty('title_property', $row) ?: '',
      'width' => $image
        ->getWidth(),
      'height' => $image
        ->getHeight(),
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DemoImage::$fileStorage protected property The file entity storage.
DemoImage::$filesystem protected property The filesystem.
DemoImage::$imageFactory protected property The image factory.
DemoImage::$migration protected property The migration plugin.
DemoImage::$moduleHandler protected property The module handler.
DemoImage::checkFile protected function Checks that a file exists and is readable.
DemoImage::copyFile protected function Copy the file.
DemoImage::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
DemoImage::createFile protected function Creates a new file from the source path.
DemoImage::findExistingFile protected function Gets an existing file entity if there is one.
DemoImage::findOrCreateFile protected function Finds existing or creates a new file.
DemoImage::getDestinationPath protected function Gets the destination path.
DemoImage::getOptionalProperty protected function Gets the value of an optional property.
DemoImage::getSourcePath protected function Gets the source path (within the module providing the migration).
DemoImage::removeTrailing protected function Removes trailing characters from given path.
DemoImage::transform public function Performs the associated process. Overrides ProcessPluginBase::transform
DemoImage::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
ProcessPluginBase::multiple public function Indicates whether the returned value requires multiple handling. Overrides MigrateProcessInterface::multiple 3
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.