You are here

public function MediaMigrateCommands::duplicateMediaImageDetection in Migrate File Entities to Media Entities 8

Calculate hash values of media entities. Can later be used together with migrate:duplicate-file-detection to find existing media files.

@command migrate:duplicate-media-detection @aliases migrate-duplicate-media

@option all Parse all existing media files or set to 0 to only process media items from previous imports.

Parameters

string $bundle: Optional media bundle, default = image.

string $field: Optional media file field, default = field_media_image.

File

src/Commands/MediaMigrateCommands.php, line 365

Class

MediaMigrateCommands
Drush 9 commands for migrate_file_to_media.

Namespace

Drupal\migrate_file_to_media\Commands

Code

public function duplicateMediaImageDetection($bundle = 'image', $field = 'field_media_image', $options = [
  'all' => TRUE,
]) {

  // Only query permanent files.
  $query = $this->connection
    ->select('media', 'me');
  $query
    ->fields('me', [
    'mid',
  ]);
  if (intval($options['all']) === 0) {
    $query
      ->leftJoin('migrate_file_to_media_mapping_media', 'm', 'm.entity_id = me.mid');
  }
  $query
    ->condition('bundle', $bundle);
  $mids = array_map(function ($mid) {
    return $mid->mid;
  }, $query
    ->execute()
    ->fetchAll());
  $medias = Media::loadMultiple($mids);
  if (empty($medias)) {
    $this
      ->output()
      ->writeln("No media found.");
  }
  else {
    foreach ($medias as $media) {

      /** @var \Drupal\media\Entity\Media $media */
      try {

        /** @var \Drupal\file\Entity\File $file */
        $file = $media->{$field}->entity;
        if ($file && !empty($binary_hash = $this
          ->calculateBinaryHash($file))) {
          $query = $this->connection
            ->select('migrate_file_to_media_mapping_media', 'map');
          $query
            ->fields('map');
          $query
            ->condition('binary_hash', $binary_hash);
          $result = $query
            ->execute()
            ->fetchObject();
          $duplicate_id = $media
            ->id();
          if ($result) {
            $existing_media = Media::load($result->entity_id);
            if ($existing_media) {
              $duplicate_id = $existing_media
                ->id();
              $this
                ->output()
                ->writeln("Duplicate found for file {$existing_media->id()}");
            }
          }

          // Check if we have an existing mapping. Update matching record.
          $upsert_query = $this->connection
            ->select('migrate_file_to_media_mapping_media', 'map');
          $upsert_query
            ->fields('map');
          $upsert_query
            ->condition('binary_hash', $binary_hash);
          $current_mapping = $upsert_query
            ->execute()
            ->fetchObject();
          if ($current_mapping) {
            $this->connection
              ->update('migrate_file_to_media_mapping_media')
              ->condition('id', $current_mapping->id)
              ->fields([
              'media_bundle' => $bundle,
              'fid' => $file
                ->id(),
              'entity_id' => $media
                ->id(),
              'target_entity_id' => $duplicate_id,
              'binary_hash' => $binary_hash,
            ])
              ->execute();
            $this
              ->output()
              ->writeln("Updated binary hash {$binary_hash} for media {$media->id()}");
          }
          else {

            // Insert new mappings for existing media entities.
            $this->connection
              ->insert('migrate_file_to_media_mapping_media')
              ->fields([
              'media_bundle' => $bundle,
              'fid' => $file
                ->id(),
              'entity_id' => $media
                ->id(),
              'target_entity_id' => $duplicate_id,
              'binary_hash' => $binary_hash,
            ])
              ->execute();
            $this
              ->output()
              ->writeln("Added binary hash {$binary_hash} for media {$media->id()}");
          }
        }
        else {
          $this
            ->output()
            ->writeln("Media empty: Skipped binary hash for media {$media->id()}");
        }
      } catch (\Exception $ex) {
        $this
          ->output()
          ->writeln("Media not found: Skipped binary hash for media {$media->id()}. Exception: {$ex->getMessage()}");
      }
    }
  }
}