You are here

class MediaFileCopy in Migrate File Entities to Media Entities 8

Copies or local file for usage in media module.

Examples:


process:
  path_to_file:
    plugin: file_copy
    source:
      - id
      - public://new/path/to/

Plugin annotation


@MigrateProcessPlugin(
  id = "media_file_copy"
)

Hierarchy

Expanded class hierarchy of MediaFileCopy

See also

\Drupal\migrate\Plugin\MigrateProcessInterface

File

src/Plugin/migrate/process/MediaFileCopy.php, line 38

Namespace

Drupal\migrate_file_to_media\Plugin\migrate\process
View source
class MediaFileCopy extends FileCopy implements ContainerFactoryPluginInterface {

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

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, array $plugin_definition, StreamWrapperManagerInterface $stream_wrappers, FileSystemInterface $file_system, MigrateProcessInterface $download_plugin, ModuleHandler $module_handler) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $stream_wrappers, $file_system, $download_plugin);
    $this->moduleHandler = $module_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('stream_wrapper_manager'), $container
      ->get('file_system'), $container
      ->get('plugin.manager.migrate.process')
      ->createInstance('download', $configuration), $container
      ->get('module_handler'));
  }

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

    // If we're stubbing a file entity, return a URI of NULL so it will get
    // stubbed by the general process.
    if ($row
      ->isStub()) {
      return NULL;
    }
    $destination_folder = $this->configuration['path'] ?? 'public://media/';
    $destination = $destination_folder . $row
      ->getSourceProperty('file_name');
    $source_file = false;

    // If the source path or URI represents a remote resource, delegate to the
    // download plugin.
    if (!$this
      ->isLocalUri($source_id)) {
      $source = $this->downloadPlugin
        ->transform([
        $source_id,
        'public://download/' . $row
          ->getSourceProperty('file_name'),
      ], $migrate_executable, $row, $destination_property);
    }
    else {
      $source_file = File::load($source_id);
      $source = $source_file
        ->getFileUri();
    }
    if ($source_file) {
      $destination = $destination_folder . $source_file
        ->getFilename();
    }

    // Ensure the source file exists, if it's a local URI or path.
    if (!file_exists($source)) {
      throw new MigrateException("File '{$source}' does not exist");
    }

    // Prepare destination folder.
    if (strpos($destination_folder, 'rokka') !== 0) {

      // Check if a writable directory exists, and if not try to create it.
      $dir = $this
        ->getDirectory($destination);

      // If the directory exists and is writable, avoid file_prepare_directory()
      // call and write the file to destination.
      if (!is_dir($dir) || !is_writable($dir)) {
        if (!\Drupal::service('file_system')
          ->prepareDirectory($dir, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS)) {
          throw new MigrateException("Could not create or write to directory '{$dir}'");
        }
      }
    }
    $final_destination = $this
      ->saveFile($source, $destination);
    if ($final_destination) {
      if ($this->moduleHandler
        ->moduleExists('crop')) {
        $this
          ->updateFocalPoint($source, $final_destination
          ->getFileUri(), $final_destination);
      }
      return $final_destination
        ->id();
    }
    throw new MigrateException("File {$source} could not be copied to {$destination}");
  }

  /**
   * Save file to a defined destination.
   */
  protected function saveFile($source, $destination, $replace = FileSystemInterface::EXISTS_RENAME) {
    $data = file_get_contents($source);
    $file = file_save_data($data, $destination, $replace);
    return $file;
  }

  /**
   * Update focal point.
   *
   * @param $uri_old
   *   Old URI.
   * @param $uri_rokka
   *   Rokka URI.
   * @param $rokka_file
   *   Rokka file.
   */
  private function updateFocalPoint($uri_old, $uri_rokka, $rokka_file) {
    try {

      /** @var \Drupal\crop\Entity\Crop $old_crop */
      $old_crop = Crop::findCrop($uri_old, 'focal_point');
      if (!empty($old_crop)) {
        $crop = Crop::create([
          'type' => 'focal_point',
          'entity_id' => $rokka_file
            ->id(),
          'entity_type' => 'file',
          'uri' => $uri_rokka,
          'height' => $old_crop->height->value,
          'width' => $old_crop->width->value,
          'x' => $old_crop->x->value,
          'y' => $old_crop->y->value,
        ]);
        $crop
          ->save();
      }
    } catch (\Exception $exception) {
      throw new MigrateException('Failed to save the focal point to rokka');
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
FileCopy::$downloadPlugin protected property An instance of the download process plugin.
FileCopy::$fileSystem protected property The file system service.
FileCopy::$streamWrapperManager protected property The stream wrapper manager service.
FileCopy::getDirectory protected function Returns the directory component of a URI or path.
FileCopy::isLocalUri protected function Determines if the given URI or path is considered local.
FileCopy::isLocationUnchanged protected function Determines if the source and destination URIs represent identical paths.
FileCopy::writeFile protected function Tries to move or copy a file.
MediaFileCopy::$moduleHandler protected property The module handler service.
MediaFileCopy::create public static function Creates an instance of the plugin. Overrides FileCopy::create
MediaFileCopy::saveFile protected function Save file to a defined destination.
MediaFileCopy::transform public function Performs the associated process. Overrides FileCopy::transform
MediaFileCopy::updateFocalPoint private function Update focal point.
MediaFileCopy::__construct public function Constructs a file_copy process plugin. Overrides FileCopy::__construct
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.