If you want to run a migration programmatically you can do so using the MigrateExecutable object. To run it you just need to feed it a migration source plugin, which you can load separately.
use Drupal\migrate\MigrateExecutable;
use Drupal\migrate\MigrateMessage;
// Get the migration plugin manager service.
$pluginManagerMigration = \Drupal::service('plugin.manager.migration');
// Create the migration of your choice.
$articleMigration = $pluginManagerMigration->createInstance('article_migration');
$articleMigrationExecutable = new MigrateExecutable($articleMigration, new MigrateMessage());
// Run the migration.
$result = $articleMigrationExecutable->import();
The migration source plugin is essentially the content of your migration source yml file, converted into an object.
If you are using the Migrate Tools plugin you can also add options to the migrate executable. For instance, to restrict by and ID list do the following (note the different MigrateExecutable object).
use Drupal\migrate_tools\MigrateExecutable;
use Drupal\migrate\MigrateMessage;
// Get the migration plugin manager service.
$pluginManagerMigration = \Drupal::service('plugin.manager.migration');
// Define the source article ID we want to migrate.
$articleId = 1;
// Create the migration of your choice.
$articleMigration = $pluginManagerMigration->createInstance('article_migration');
$articleMigrationExecutable = new MigrateExecutable($articleMigration, new MigrateMessage(), ['idlist' => $articleId]);
// Run the migration.
$result = $articleMigrationExecutable->import();
This executable will run through the migration in the usual way. The return value from the import() method is in integer, detailing how the migration went. Use this to adapt your code to a migration pass or failure.
Add new comment