How to programmatically generate Migration entities and config entities

You, DrupalDrupal entity api
Back

In a recent event I had a requirement to dynamically create Migrations within the entity_update hook. So for that I used couple of existing functions within Drupal to get the list of available migrations and create new migration based on those settings.

I used the following function to get the list of Migrations within Drupal.

/**
 * Retrieve a list of active migrations.
 *
 * @param string $migration_ids
 *  Comma-separated list of migrations - if present, return only these migrations.
 *
 * @return MigrationInterface[][]
 *   An array keyed by migration group, each value containing an array of
 *   migrations or an empty array if no migrations match the input criteria.
 */
function _MODULENAME_migration_list($migration_ids = '') {
  $manager = \Drupal::service('plugin.manager.migration');
  $plugins = $manager->createInstances([]);
  $matched_migrations = [];

  // Get the set of migrations that may be filtered.
  if (empty($migration_ids)) {
    $matched_migrations = $plugins;
  }
  else {
    // Get the requested migrations.
    $migration_ids = explode(',', Unicode::strtolower($migration_ids));
    foreach ($plugins as $id => $migration) {
      if (in_array(Unicode::strtolower($id), $migration_ids)) {
        $matched_migrations[$id] = $migration;
      }
    }
  }

  // Do not return any migrations which fail to meet requirements.
  /** @var \Drupal\migrate\Plugin\Migration $migration */
  foreach ($matched_migrations as $id => $migration) {
    if ($migration->getSourcePlugin() instanceof RequirementsInterface) {
      try {
        $migration->getSourcePlugin()->checkRequirements();
      }
      catch (RequirementsException $e) {
        unset($matched_migrations[$id]);
      }
    }
  }

  // Filters the matched migrations if a group or a tag has been input.
  if (!empty($filter['migration_group']) || !empty($filter['migration_tags'])) {
    // Get migrations in any of the specified groups and with any of the
    // specified tags.
    foreach ($filter as $property => $values) {
      if (!empty($values)) {
        $filtered_migrations = [];
        foreach ($values as $search_value) {
          foreach ($matched_migrations as $id => $migration) {
            // Cast to array because migration_tags can be an array.
            $configured_values = (array) $migration->get($property);
            $configured_id = (in_array($search_value, $configured_values)) ? $search_value : 'default';
            if (empty($search_value) || $search_value == $configured_id) {
              if (empty($migration_ids) || in_array(Unicode::strtolower($id), $migration_ids)) {
                $filtered_migrations[$id] = $migration;
              }
            }
          }
        }
        $matched_migrations = $filtered_migrations;
      }
    }
  }

  // Sort the matched migrations by group.
  if (!empty($matched_migrations)) {
    foreach ($matched_migrations as $id => $migration) {
      $configured_group_id = empty($migration->get('migration_group')) ? 'default' : $migration->get('migration_group');
      $migrations[$configured_group_id][$id] = $migration;
    }
  }
  return isset($migrations) ? $migrations : [];
}

Now let's create the Migration programmatically within the hook entity update.

/**
 * Implements hook_entity_update().
 */
function MODULENAME_entity_update(EntityInterface $entity) {
  if($entity->getType() == 'CONTENT_TYPE'){
    $migrations_groups = _MODULENAME_migration_list('import_leaderboard_template');
    if(!empty($migrations_load = _MODULENAME_migration_list('import_leaderboard_' . $entity->Id()))){
      foreach($migrations_load as $migrations){
        foreach($migrations as $machinename => $migration){
          Drupal::configFactory()->getEditable('migrate_plus.migration.' . $machinename)->delete();
        }
      }
    }
    foreach($migrations_groups as $migrations){
      foreach($migrations as $migration_id => $migration){
        $entity_array['id'] = 'import_leaderboard_' . $entity->Id();
        $entity_array['class'] = $migration->get('class');
        $entity_array['cck_plugin_method'] = $migration->get('cck_plugin_method');
        $entity_array['field_plugin_method'] = $migration->get('field_plugin_method');
        $entity_array['migration_group'] = 'regatta_import_leaderboards';
        $entity_array['migration_tags'] = $migration->get('migration_tags');
        $entity_array['label'] = 'Import Leaderboards for ' . $entity->label();
        $source = $migration->getSourceConfiguration();
        $entity_array['source'] = $source;
        $entity_array['destination'] = $migration->getDestinationConfiguration();
        $entity_array['process'] = $migration->get('process');
        $entity_array['migration_dependencies'] = $migration->getMigrationDependencies();
        $migration_entity = Migration::create($entity_array);
        $migration_entity->save();
      }
    }
  }
}

© Heshan Wanigasooriya.RSS

🍪 This site does not track you.