Skip to content

Instantly share code, notes, and snippets.

@vladdancer
Forked from vasi/dry_run.php
Created September 13, 2021 16:49
Show Gist options
  • Save vladdancer/bbcef87493af15512a4711c0e6f18b6b to your computer and use it in GitHub Desktop.
Save vladdancer/bbcef87493af15512a4711c0e6f18b6b to your computer and use it in GitHub Desktop.
Drupal migrate dry run
<?php
use Drupal\migrate_plus\Event\MigrateEvents as MigratePlusEvents;
use Drupal\migrate_plus\Event\MigratePrepareRowEvent;
use Drupal\migrate\Plugin\MigrateIdMapInterface;
function dry_run_migration($migration_id) {
// Get the migration source.
$migrationManager = \Drupal::service('plugin.manager.config_entity_migration');
$migration = $migrationManager->createInstance($migration_id);
$source = $migration->getSourcePlugin();
// Usually, the source will automatically skip rows that haven't changed,
// since we don't have to do anything with them.
// But to detect deletions, we need to see every single row--so we mark each
// row as 'changed', to make sure they're not skipped.
$dispatcher = \Drupal::service('event_dispatcher');
$dispatcher->addListener(MigratePlusEvents::PREPARE_ROW,
function(MigratePrepareRowEvent $event) {
$row = $event->getRow();
if ($row->getIdMap()) {
$row->setIdMap([
'source_row_status' => MigrateIdMapInterface::STATUS_NEEDS_UPDATE
] + $row->getIdMap());
}
}
);
// Look at each row to see if it's new or updated.
$seen = [];
foreach ($source as $row) {
$ids = implode(', ', array_values($row->getSourceIdValues()));
if (empty($row->getIdMap()['original_hash'])) {
printf("NEW: $ids\n");
}
elseif ($row->changed()) {
printf("UPDATED: $ids\n");
}
// Mark this row as seen.
$seen[$ids] = TRUE;
}
// Anything that we previously migrated, but wasn't in our source,
// must have been deleted.
$id_map = $migration->getIdMap();
foreach ($migration->getIdMap() as $row) {
if (empty($id_map->currentDestination())) {
// When previously processing this row, nothing was imported.
continue;
}
$ids = implode(', ', array_values($id_map->currentSource()));
if (empty($seen[$ids])) {
printf("DELETED: $ids\n");
}
}
}
dry_run_migration('my_test_migration');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment