Execute Migrate programmatically

By kenneth, Fri, 06/21/2024 - 15:35
<?php

use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\MigrateMessage;
use Drupal\migrate\MigrateExecutable;

$manager = \Drupal::service('plugin.manager.migration');
$migration_ids = ['migration_machine_name'];
foreach ($migration_ids as $migration_id) {
  $migration = $manager->createInstance($migration_id);
  // update existing entity imported.
  $migration->getIdMap()->prepareUpdate();
  $executable = new MigrateExecutable($migration, new MigrateMessage());

  try {
    // Run the migration.
    $executable->import();
  }
  catch (\Exception $e) {
    $migration->setStatus(MigrationInterface::STATUS_IDLE);
  }
}