Skip to content

Instantly share code, notes, and snippets.

@heitoralthmann
Created April 15, 2021 13:15
Show Gist options
  • Save heitoralthmann/e8e30fcc535074ba48738ed77b21c548 to your computer and use it in GitHub Desktop.
Save heitoralthmann/e8e30fcc535074ba48738ed77b21c548 to your computer and use it in GitHub Desktop.
Drupal 8 - Migration - How to run a migration programmatically (including update and sync operations)
<?php
use Drupal\migrate\MigrateMessage;
use Drupal\migrate_tools\MigrateExecutable;
/**
* Runs a migration.
*
* @param string $migration_name
* The name of the migration to run.
* @param string $operation
* The migration operation to execute (import|update|sync).
*/
function run_migration(string $migration_name, string $operation = 'import') {
/** @var \Drupal\migrate\Plugin\MigrationPluginManager $plugin_manager_migration */
$plugin_manager_migration = \Drupal::service('plugin.manager.migration');
$import_options = [];
if ($migration = $plugin_manager_migration->createInstance($migration_name)) {
switch ($operation) {
case 'update':
$migration->getIdMap()->prepareUpdate();
$import_options['update'] = TRUE;
break;
case 'sync':
$migration->set('syncSource', TRUE);
$import_options['sync'] = TRUE;
}
$executable = new MigrateExecutable($migration, new MigrateMessage(), $import_options);
$executable->import();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment