You are here

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

Create media destination fields.

@command migrate:file-media-fields @aliases mf2m

Parameters

$entity_type:

$bundle:

$source_field_type:

$target_media_bundle:

File

src/Commands/MediaMigrateCommands.php, line 91

Class

MediaMigrateCommands
Drush 9 commands for migrate_file_to_media.

Namespace

Drupal\migrate_file_to_media\Commands

Code

public function migrateFileFields($entity_type, $bundle, $source_field_type, $target_media_bundle) {
  $this
    ->output()
    ->writeln("Creating media reference fields for {$entity_type} : {$bundle}.");
  $bundle_fields = $this->entityFieldManager
    ->getFieldDefinitions($entity_type, $bundle);

  // Gather a list of all target fields.
  $map = \Drupal::service('entity_field.manager')
    ->getFieldMapByFieldType($source_field_type);
  $source_fields = [];
  foreach ($map[$entity_type] as $name => $data) {
    foreach ($data['bundles'] as $bundle_name) {
      if ($bundle_name == $bundle) {
        $target_field_name = substr($name, 0, FieldStorageConfig::NAME_MAX_LENGTH - 6) . '_media';
        $source_fields[$target_field_name] = $bundle_fields[$name];
        $this
          ->output()
          ->writeln('Found field: ' . $name);
      }
    }
  }
  $map = \Drupal::service('entity_field.manager')
    ->getFieldMapByFieldType('entity_reference');
  $media_fields = [];
  foreach ($map[$entity_type] as $name => $data) {
    foreach ($data['bundles'] as $bundle_name) {
      if ($bundle_name == $bundle) {
        $field_settings = $bundle_fields[$name];
        $target_bundles = $field_settings
          ->getSettings()['handler_settings']['target_bundles'];
        $handler = $field_settings
          ->getSettings()['handler'];
        if (!empty($target_bundles)) {
          foreach ($target_bundles as $target_bundle) {
            if ($handler == 'default:media' && $target_bundle == $target_media_bundle) {

              // $media_fields[$name] = $field_settings;.
              $this
                ->output()
                ->writeln('Found existing media field: ' . $name);
            }
          }
        }
      }
    }
  }

  // Create missing fields.
  $missing_fields = array_diff_key($source_fields, $media_fields);
  foreach ($missing_fields as $new_field_name => $field) {
    try {
      $new_field = $this
        ->createMediaField($entity_type, $bundle, $field, $new_field_name, $target_media_bundle);
    } catch (\Exception $ex) {
      $this
        ->output()
        ->writeln("Error while creating media field: {$new_field_name}.");
    }
    if (!empty($new_field)) {
      $this
        ->output()
        ->writeln("Created media field: {$new_field->getName()}.");
    }
  }
  $this
    ->output()
    ->writeln("Clearing caches.");
  drupal_flush_all_caches();
}