-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
MigrateRunnerCommands.php
879 lines (832 loc) · 33.1 KB
/
MigrateRunnerCommands.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
<?php
namespace Drush\Drupal\Commands\core;
use Consolidation\AnnotatedCommand\CommandData;
use Consolidation\AnnotatedCommand\CommandError;
use Consolidation\OutputFormatters\StructuredData\RowsOfFields;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Datetime\DateFormatter;
use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
use Drupal\Core\KeyValueStore\KeyValueStoreInterface;
use Drupal\migrate\Exception\RequirementsException;
use Drupal\migrate\MigrateMessageInterface;
use Drupal\migrate\Plugin\MigrateIdMapInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\MigrationPluginManagerInterface;
use Drupal\migrate\Plugin\RequirementsInterface;
use Drush\Commands\DrushCommands;
use Drush\Drupal\Migrate\MigrateExecutable;
use Drush\Drupal\Migrate\MigrateMessage;
use Drush\Drupal\Migrate\MigrateUtils;
use Drush\Utils\StringUtils;
use Webmozart\PathUtil\Path;
/**
* Migrate runner commands.
*/
class MigrateRunnerCommands extends DrushCommands
{
/**
* Migration plugin manager service.
*/
protected ?MigrationPluginManagerInterface $migrationPluginManager;
/**
* Date formatter service.
*/
protected DateFormatter $dateFormatter;
/**
* The key-value store service.
*/
protected KeyValueStoreInterface $keyValue;
/**
* Migrate message service.
*/
protected MigrateMessageInterface $migrateMessage;
/**
* Constructs a new class instance.
*
* @param DateFormatter $dateFormatter
* Date formatter service.
* @param KeyValueFactoryInterface $keyValueFactory
* The key-value factory service.
* @param MigrationPluginManagerInterface|null $migrationPluginManager
* The migration plugin manager service.
*/
public function __construct(DateFormatter $dateFormatter, KeyValueFactoryInterface $keyValueFactory, ?MigrationPluginManagerInterface $migrationPluginManager = null)
{
parent::__construct();
$this->dateFormatter = $dateFormatter;
$this->keyValue = $keyValueFactory->get('migrate_last_imported');
$this->migrationPluginManager = $migrationPluginManager;
}
/**
* List all migrations with current status.
*
* @command migrate:status
*
* @param string|null $migrationIds
* Restrict to a comma-separated list of migrations. Optional.
*
* @option tag A comma-separated list of migration tags to list. If only
* <info>--tag</info> is provided, all tagged migrations will be listed,
* grouped by tags.
* @option names-only [Deprecated, use --field=id instead] Only return names, not all the details (faster).
*
* @usage migrate:status
* Retrieve status for all migrations
* @usage migrate:status --tag
* Retrieve status for all migrations, grouped by tag
* @usage migrate:status --tag=user,main_content
* Retrieve status for all migrations tagged with <info>user</info> or
* <info>main_content</info>
* @usage migrate:status classification,article
* Retrieve status for specific migrations
* @usage migrate:status --field=id
* Retrieve a raw list of migration IDs.
* @usage ms --fields=id,status --format=json
* Retrieve a Json serialized list of migrations, each item containing only the migration ID and its status.
*
* @aliases ms,migrate-status
*
* @topics docs:migrate
*
* @validate-module-enabled migrate
*
* @field-labels
* id: Migration ID
* status: Status
* total: Total
* imported: Imported
* needing_update: Needing update
* unprocessed: Unprocessed
* last_imported: Last Imported
* @default-fields id,status,total,imported,unprocessed,last_imported
* @filter-default-field status
* @return RowsOfFields
* Migrations status formatted as table.
* @version 10.4
*
* @throws \Exception
* If --names-only is used with --field having other value than 'id'.
*/
public function status(?string $migrationIds = null, array $options = [
'tag' => self::REQ,
'names-only' => false,
]): RowsOfFields
{
// The --names-only option takes precedence over --fields.
if ($options['names-only']) {
if ($options['field'] && $options['field'] !== 'id') {
throw new \Exception("Cannot use --names-only with --field={$options['field']}.");
}
$deprecationMessage = 'The --names-only option is deprecated in Drush 10.5.1 and is removed from Drush 11.0.0. Use --field=id instead.';
$this->logger()->warning($deprecationMessage);
@trigger_error($deprecationMessage, E_USER_DEPRECATED);
$fields = ['id'];
} elseif ($options['field']) {
$fields = [$options['field']];
} elseif ($options['fields']) {
$fields = StringUtils::csvToArray($options['fields']);
}
$list = $this->getMigrationList($migrationIds, $options['tag']);
$table = [];
// Take it one tag at a time, listing the migrations within each tag.
foreach ($list as $tag => $migrations) {
if ($tag) {
$table[] = $this->padTableRow([
'id' => dt('Tag: @name', ['@name' => $tag])
], $fields);
}
ksort($migrations);
foreach ($migrations as $migration) {
$row = [];
foreach ($fields as $field) {
switch ($field) {
case 'id':
$row[$field] = ($tag ? ' ' : '') . $migration->id();
break;
case 'status':
$row[$field] = $migration->getStatusLabel();
break;
case 'total':
$sourceRowsCount = $this->getMigrationSourceRowsCount($migration);
$row[$field] = $sourceRowsCount !== null ? $sourceRowsCount : dt('N/A');
break;
case 'needing_update':
$row[$field] = $this->getMigrationNeedingUpdateCount($migration);
break;
case 'unprocessed':
$unprocessedCount = $this->getMigrationUnprocessedCount($migration);
$row[$field] = $unprocessedCount !== null ? $unprocessedCount : dt('N/A');
break;
case 'imported':
$importedCount = $this->getMigrationImportedCount($migration);
if ($importedCount === null) {
// Next migration.
continue 2;
}
$sourceRowsCount = $sourceRowsCount ?? $this->getMigrationSourceRowsCount($migration);
if ($sourceRowsCount > 0 && $importedCount > 0) {
$importedCount .= ' (' . round(($importedCount / $sourceRowsCount) * 100, 1) . '%)';
}
$row[$field] = $importedCount;
break;
case 'last_imported':
$row[$field] = $this->getMigrationLastImportedTime($migration);
break;
}
}
$table[] = $row;
}
// Add an empty row after a tag group.
if ($tag) {
$table[] = $this->padTableRow([], $fields);
}
}
return new RowsOfFields($table);
}
/**
* Returns the migration source rows count.
*
* @param MigrationInterface $migration
* The migration plugin instance.
* @return int|null
* The migration source rows count or null if the source is uncountable or
* the source count couldn't be retrieved.
*/
protected function getMigrationSourceRowsCount(MigrationInterface $migration): ?int
{
try {
$sourceRowsCount = $migration->getSourcePlugin()->count();
// -1 indicates uncountable sources.
if ($sourceRowsCount === -1) {
return null;
}
return $sourceRowsCount;
} catch (\Exception $exception) {
$arguments = [
'@migration' => $migration->id(),
'@message' => $exception->getMessage(),
];
$this->logger()->error(dt('Could not retrieve source count from @migration: @message', $arguments));
return null;
}
}
/**
* Returns the number of items that needs update.
*
* @param MigrationInterface $migration
* The migration plugin instance.
*
* @return int|null
* The number of items that needs update.
*/
protected function getMigrationNeedingUpdateCount(MigrationInterface $migration): int
{
$map = $migration->getIdMap();
return count($map->getRowsNeedingUpdate($map->processedCount()));
}
/**
* Returns the number of unprocessed items.
*
* @param MigrationInterface $migration
* The migration plugin instance.
*
* @return int|null
* The number of unprocessed items or null if it cannot be determined.
*/
protected function getMigrationUnprocessedCount(MigrationInterface $migration): ?int
{
$sourceRowsCount = $this->getMigrationSourceRowsCount($migration);
if ($sourceRowsCount === null) {
return null;
}
return $sourceRowsCount - $migration->getIdMap()->processedCount();
}
/**
* Returns the number of imported items.
*
* @param MigrationInterface $migration
* The migration plugin instance.
*
* @return int|null
* The number of imported items or null if it cannot be determined.
*/
protected function getMigrationImportedCount(MigrationInterface $migration): ?int
{
try {
return $migration->getIdMap()->importedCount();
} catch (\Exception $exception) {
$arguments = [
'@migration' => $migration->id(),
'@message' => $exception->getMessage(),
];
$this->logger()->error(dt('Failure retrieving information on @migration: @message', $arguments));
return null;
}
}
/**
* Returns the last imported date/time if any.
*
* @param MigrationInterface $migration
* The migration plugin instance.
*
* @return string
* The last imported date/time if any.
*/
protected function getMigrationLastImportedTime(MigrationInterface $migration): string
{
if ($lastImported = $this->keyValue->get($migration->id(), '')) {
$lastImported = $this->dateFormatter->format(round($lastImported / 1000), 'custom', 'Y-m-d H:i:s');
}
return $lastImported;
}
/**
* Pads an incomplete table row with empty cells.
*
* @param array $row
* The row to be prepared.
* @param array $fields
* The table columns.
*
* @return array
* The complete table row.
*/
protected function padTableRow(array $row, array $fields): array
{
foreach (array_diff_key(array_flip($fields), $row) as $field => $delta) {
$row[$field] = null;
}
return $row;
}
/**
* Perform one or more migration processes.
*
* @command migrate:import
*
* @param string|null $migrationIds
* Comma-separated list of migration IDs.
*
* @option all Process all migrations.
* @option tag A comma-separated list of migration tags to import
* @option limit Limit on the number of items to process in each migration
* @option feedback Frequency of progress messages, in items processed
* @option idlist Comma-separated list of IDs to import. As an ID may have more than one column, concatenate the columns with the colon ':' separator
* @option update In addition to processing unprocessed items from the source, update previously-imported items with the current data
* @option force Force an operation to run, even if all dependencies are not satisfied
* @option execute-dependencies Execute all dependent migrations first.
* @option timestamp Show progress ending timestamp in progress messages
* @option total Show total processed item number in progress messages
* @option progress Show progress bar
* @option delete Delete destination records missed from the source. Not compatible with --limit and --idlist options, and high_water_property source configuration key.
*
* @usage migrate:import --all
* Perform all migrations
* @usage migrate:import --all --no-progress
* Perform all migrations but avoid the progress bar
* @usage migrate:import --tag=user,main_content
* Import all migrations tagged with <info>user</info> and <info>main_content</info> tags
* @usage migrate:import classification,article
* Import new terms and nodes using migration <info>classification</info> and <info>article</info>
* @usage migrate:import user --limit=2
* Import no more than 2 users using the <info>user</info> migration
* @usage migrate:import user --idlist=5
* Import the user record with source ID 5
* @usage migrate:import node_revision --idlist=1:2,2:3,3:5
* Import the node revision record with source IDs [1,2], [2,3], and [3,5]
* @usage migrate:import user --limit=50 --feedback=20
* Import 50 users and show process message every 20th record
* @usage migrate:import --all --delete
* Perform all migrations and delete the destination items that are missing from source
*
* @aliases mim,migrate-import
*
* @topics docs:migrate
*
* @validate-module-enabled migrate
*
* @version 10.4
*
* @throws \Exception
* When not enough options were provided or no migration was found.
*/
public function import(?string $migrationIds = null, array $options = ['all' => false, 'tag' => self::REQ, 'limit' => self::REQ, 'feedback' => self::REQ, 'idlist' => self::REQ, 'update' => false, 'force' => false, 'execute-dependencies' => false, 'timestamp' => false, 'total' => false, 'progress' => true, 'delete' => false]): void
{
$tags = $options['tag'];
$all = $options['all'];
if (!$all && !$migrationIds && !$tags) {
throw new \Exception(dt('You must specify --all, --tag or one or more migration names separated by commas'));
}
if (!$list = $this->getMigrationList($migrationIds, $options['tag'])) {
throw new \Exception(dt('No migrations found.'));
}
$userData = [
'options' => array_intersect_key($options, array_flip([
'limit',
'feedback',
'idlist',
'update',
'force',
'timestamp',
'total',
'progress',
'delete',
])),
'execute_dependencies' => $options['execute-dependencies'],
];
// Include the file providing a migrate_prepare_row hook implementation.
require_once Path::join(DRUSH_BASE_PATH, 'src/Drupal/Migrate/migrate_runner.inc');
// If the 'migrate_prepare_row' hook implementations are already cached,
// make sure that system_migrate_prepare_row() is picked-up.
\Drupal::moduleHandler()->resetImplementations();
foreach ($list as $migrations) {
array_walk($migrations, [static::class, 'executeMigration'], $userData);
}
}
/**
* Executes a single migration.
*
* If the --execute-dependencies option was given, the migration's
* dependencies will also be executed first.
*
* @param MigrationInterface $migration
* The migration to execute.
* @param string $migrationId
* The migration ID (not used, just an artifact of array_walk()).
* @param array $userData
* Additional data passed to the callback.
*
* @throws \Exception
* If there are failed migrations.
*/
protected function executeMigration(MigrationInterface $migration, string $migrationId, array $userData): void
{
static $executedMigrations = [];
if ($userData['execute_dependencies']) {
$dependencies = $migration->getMigrationDependencies()['required'];
// Remove already executed migrations.
$dependencies = array_diff($dependencies, $executedMigrations);
if ($dependencies) {
$requiredMigrations = $this->migrationPluginManager->createInstances($dependencies);
array_walk($requiredMigrations, [static::class, __FUNCTION__], $userData);
}
}
if (!empty($userData['options']['force'])) {
$migration->set('requirements', []);
}
if (!empty($userData['options']['update'])) {
if (empty($userData['options']['idlist'])) {
$migration->getIdMap()->prepareUpdate();
} else {
$sourceIdValuesList = MigrateUtils::parseIdList($userData['options']['idlist']);
$keys = array_keys($migration->getSourcePlugin()->getIds());
foreach ($sourceIdValuesList as $sourceIdValues) {
$migration->getIdMap()->setUpdate(array_combine($keys, $sourceIdValues));
}
}
}
$executable = new MigrateExecutable($migration, $this->getMigrateMessage(), $this->output(), $userData['options']);
// drush_op() provides --simulate support.
drush_op([$executable, 'import']);
if ($count = $executable->getFailedCount()) {
// Nudge Drush to use a non-zero exit code.
throw new \Exception(dt('!name migration: !count failed.', ['!name' => $migrationId, '!count' => $count]));
}
// Keep track of executed migrations.
$executedMigrations[] = $migrationId;
}
/**
* Rollback one or more migrations.
*
* @command migrate:rollback
*
* @param string|null $migrationIds
* Comma-separated list of migration IDs.
*
* @option all Process all migrations.
* @option tag A comma-separated list of migration tags to rollback
* @option feedback Frequency of progress messages, in items processed
* @option idlist Comma-separated list of IDs to rollback. As an ID may have more than one column, concatenate the columns with the colon ':' separator
* @option progress Show progress bar
*
* @usage migrate:rollback --all
* Rollback all migrations
* @usage migrate:rollback --all --no-progress
* Rollback all migrations but avoid the progress bar
* @usage migrate:rollback --tag=user,main_content
* Rollback all migrations tagged with <info>user</info> and <info>main_content</info> tags
* @usage migrate:rollback classification,article
* Rollback terms and nodes imported by <info>classification</info> and <info>article</info> migrations
* @usage migrate:rollback user --idlist=5
* Rollback imported user record with source ID 5
*
* @aliases mr,migrate-rollback
*
* @topics docs:migrate
*
* @validate-module-enabled migrate
*
* @version 10.4
*
* @throws \Exception
* When not enough options were provided.
*/
public function rollback(?string $migrationIds = null, array $options = ['all' => false, 'tag' => self::REQ, 'feedback' => self::REQ, 'idlist' => self::REQ, 'progress' => true]): void
{
$tags = $options['tag'];
$all = $options['all'];
if (!$all && !$migrationIds && !$tags) {
throw new \Exception(dt('You must specify --all, --tag, or one or more migration names separated by commas'));
}
if (!$list = $this->getMigrationList($migrationIds, $options['tag'])) {
$this->logger()->error(dt('No migrations found.'));
}
$executableOptions = array_intersect_key(
$options,
array_flip(['feedback', 'idlist', 'progress'])
);
foreach ($list as $migrations) {
// Rollback in reverse order.
$migrations = array_reverse($migrations);
foreach ($migrations as $migration) {
$executable = new MigrateExecutable($migration, $this->getMigrateMessage(), $this->output(), $executableOptions);
// drush_op() provides --simulate support.
drush_op([$executable, 'rollback']);
}
}
}
/**
* Stop an active migration operation.
*
* @command migrate:stop
*
* @param string $migrationId
* The ID of migration to stop.
*
* @aliases mst,migrate-stop
*
* @topics docs:migrate
*
* @validate-module-enabled migrate
* @validate-migration-id
* @version 10.4
*
* @throws PluginException
*/
public function stop(string $migrationId): void
{
/** @var MigrationInterface $migration */
$migration = $this->migrationPluginManager->createInstance($migrationId);
switch ($migration->getStatus()) {
case MigrationInterface::STATUS_IDLE:
$this->logger()->warning(dt('Migration @id is idle', ['@id' => $migrationId]));
break;
case MigrationInterface::STATUS_DISABLED:
$this->logger()->warning(dt('Migration @id is disabled', ['@id' => $migrationId]));
break;
case MigrationInterface::STATUS_STOPPING:
$this->logger()->warning(dt('Migration @id is already stopping', ['@id' => $migrationId]));
break;
default:
$migration->interruptMigration(MigrationInterface::RESULT_STOPPED);
$this->logger()->success(dt('Migration @id requested to stop', ['@id' => $migrationId]));
break;
}
}
/**
* Reset an active migration's status to idle.
*
* @command migrate:reset-status
*
* @param string $migrationId
* The ID of migration to reset.
*
* @aliases mrs,migrate-reset-status
*
* @topics docs:migrate
*
* @validate-module-enabled migrate
* @validate-migration-id
* @version 10.4
*
* @throws PluginException
*/
public function resetStatus(string $migrationId): void
{
/** @var MigrationInterface $migration */
$migration = $this->migrationPluginManager->createInstance($migrationId);
$status = $migration->getStatus();
if ($status == MigrationInterface::STATUS_IDLE) {
$this->logger()->warning(dt('Migration @id is already Idle', ['@id' => $migrationId]));
} else {
$migration->setStatus(MigrationInterface::STATUS_IDLE);
$this->logger()->success(dt('Migration @id reset to Idle', ['@id' => $migrationId]));
}
}
/**
* View any messages associated with a migration.
*
* @command migrate:messages
*
* @param string $migrationId
* The ID of the migration.
*
* @option idlist Comma-separated list of IDs to import. As an ID may have
* more than one column, concatenate the columns with the colon ':'
* separator.
*
* @usage migrate:messages article
* Show all messages for the <info>article</info> migration
* @usage migrate:messages article --idlist=5
* Show messages related to article record with source ID 5.
* @usage migrate:messages node_revision --idlist=1:2,2:3,3:5
* Show messages related to node revision records with source IDs [1,2],
* [2,3], and [3,5].
* @usage migrate:messages custom_node_revision --idlist=1:"r:1",2:"r:3"
* Show messages related to node revision records with source IDs
* [1,"r:1"], and [2,"r:3"].
*
* @aliases mmsg,migrate-messages
*
* @topics docs:migrate
*
* @validate-module-enabled migrate
* @validate-migration-id
* @version 10.4
*
* @field-labels
* level: Level
* source_ids: Source ID(s)
* destination_ids: Destination ID(s)
* message: Message
* hash: Source IDs hash
* @default-fields level,source_ids,destination_ids,message,hash
*
* @return RowsOfFields
* Migration messages status formatted as table.
*
* @throws PluginException
*/
public function messages(string $migrationId, array $options = ['idlist' => self::REQ]): RowsOfFields
{
/** @var MigrationInterface $migration */
$migration = $this->migrationPluginManager->createInstance($migrationId);
$idMap = $migration->getIdMap();
$sourceIdKeys = $this->getSourceIdKeys($idMap);
$table = [];
if (empty($sourceIdKeys)) {
// Cannot find one item to extract keys from, no need to process
// messages on an empty ID map.
return new RowsOfFields($table);
}
if (!empty($options['idlist'])) {
// There is no way to retrieve a filtered set of messages from an ID
// map on Drupal core, right now. Even if using
// \Drush\Drupal\Migrate\MigrateIdMapFilter does the right thing
// filtering the data on the ID map, sadly its getMessages() method
// does not take it into account the iterator, and retrieves data
// directly, e.g. at SQL ID map plugin. On the other side Drupal
// core's \Drupal\migrate\Plugin\MigrateIdMapInterface only allows
// to filter by one source IDs set, and not by multiple, on
// getMessages(). For now, go over known IDs passed directly, one at
// a time a workaround, at the cost of more queries in the usual SQL
// ID map, which is likely OK for its use, to show only few source
// IDs messages.
foreach (MigrateUtils::parseIdList($options['idlist']) as $sourceIdValues) {
foreach ($idMap->getMessages($sourceIdValues) as $row) {
$table[] = $this->preprocessMessageRow($row, $sourceIdKeys);
}
}
return new RowsOfFields($table);
}
foreach ($idMap->getMessages() as $row) {
$table[] = $this->preprocessMessageRow($row, $sourceIdKeys);
}
return new RowsOfFields($table);
}
/**
* Preprocesses migrate message rows.
*
* Given an item inside the list generated by
* MigrateIdMapInterface::getMessages(), prepare it for display.
*
* @param \StdClass $row
* A message to process.
* @param array $sourceIdKeys
* The source IDs keys, for reference.
*
* @see \Drupal\migrate\Plugin\MigrateIdMapInterface::getMessages()
*/
protected function preprocessMessageRow(\StdClass $row, array $sourceIdKeys): array
{
unset($row->msgid);
$row = (array) $row;
// If the message includes useful IDs don't print the hash.
if (count($sourceIdKeys) === count(array_intersect_key($sourceIdKeys, $row))) {
unset($row['source_ids_hash']);
}
$sourceIds = $destinationIds = [];
foreach ($row as $key => $value) {
if (str_starts_with($key, 'src_')) {
$sourceIds[$key] = $value;
}
if (str_starts_with($key, 'dest_')) {
$destinationIds[$key] = $value;
}
}
$row['source_ids'] = implode(' : ', $sourceIds);
$row['destination_ids'] = implode(' : ', $destinationIds);
return $row;
}
/**
* List the fields available for mapping in a source.
*
* @command migrate:fields-source
*
* @param string $migrationId
* The ID of the migration.
*
* @usage migrate:fields-source article
* List fields for the source in the article migration
*
* @aliases mfs,migrate-fields-source
*
* @topics docs:migrate
*
* @validate-module-enabled migrate
* @validate-migration-id
*
* @field-labels
* machine_name: Field name
* description: Description
* @default-fields machine_name,description
* @version 10.4
*
* @return RowsOfFields
* Source fields of the given migration.
*
* @throws PluginException
*/
public function fieldsSource(string $migrationId): RowsOfFields
{
/** @var MigrationInterface $migration */
$migration = $this->migrationPluginManager->createInstance($migrationId);
$source = $migration->getSourcePlugin();
$table = [];
foreach ($source->fields() as $machineName => $description) {
$table[] = [
'machine_name' => $machineName,
'description' => strip_tags($description),
];
}
return new RowsOfFields($table);
}
/**
* Retrieves a list of active migrations.
*
* @param string|null $migrationIds A comma-separated list of migration IDs. If omitted, will return all
* migrations.
* @param string|null $tags
* A comma separated list of tags.
*
* @return MigrationInterface[][]
* An array keyed by migration tag, each value containing an array of
* migrations or an empty array if no migrations match the input criteria.
*
* @throws PluginException
*/
protected function getMigrationList(?string $migrationIds, ?string $tags): array
{
$migrationIds = StringUtils::csvToArray((string) $migrationIds);
$migrations = $this->migrationPluginManager->createInstances($migrationIds);
// Check for invalid migration IDs.
if ($invalidMigrations = array_diff_key(array_flip($migrationIds), $migrations)) {
throw new \InvalidArgumentException('Invalid migration IDs: ' . implode(', ', array_flip($invalidMigrations)));
}
foreach ($migrations as $migrationId => $migration) {
try {
$sourcePlugin = $migration->getSourcePlugin();
if ($sourcePlugin instanceof RequirementsInterface) {
$sourcePlugin->checkRequirements();
}
} catch (RequirementsException $exception) {
$this->logger()->debug("Migration '$migrationId' is skipped as its source plugin has missed requirements: {$exception->getRequirementsString()}");
unset($migrations[$migrationId]);
}
}
// If --tag was not passed, don't group on tags, use a single empty tag.
if ($tags === null) {
return [null => $migrations];
}
$tags = array_filter(array_map('trim', explode(',', $tags)));
$list = [];
foreach ($migrations as $migrationId => $migration) {
$migrationTags = $migration->getMigrationTags();
$commonTags = array_intersect($tags, $migrationTags);
if (!$commonTags) {
// Skip if migration is not tagged with any of the passed tags.
continue;
}
foreach ($commonTags as $tag) {
$list[$tag][$migrationId] = $migration;
}
}
ksort($list);
return $list;
}
/**
* Returns the migrate message logger.
*
* @return MigrateMessageInterface
* The migrate message logger.
*/
protected function getMigrateMessage(): MigrateMessageInterface
{
if (!isset($this->migrateMessage)) {
$this->migrateMessage = new MigrateMessage($this->logger());
}
return $this->migrateMessage;
}
/**
* Get the source ID keys.
*
* @param MigrateIdMapInterface $idMap
* The migration ID map.
*
* @return string[]
* The source ID keys.
*/
protected function getSourceIdKeys(MigrateIdMapInterface $idMap): array
{
if (iterator_count($idMap) === 0) {
// E.g. when the migration has not yet been executed. the ID map is
// empty. do not try to process it.
return [];
}
$idMap->rewind();
$columns = $idMap->currentSource();
$sourceIdKeys = array_map(static function ($id) {
return "src_$id";
}, array_keys($columns));
return array_combine($sourceIdKeys, $sourceIdKeys);
}
/**
* Validates a migration ID is valid.
*
* If the argument to be validated is not named migrationId, pass the
* argument name as the value of the annotation.
*
* @hook validate @validate-migration-id
*
* @param CommandData $commandData
*
* @return CommandError|null
*/
public function validateMigrationId(CommandData $commandData): ?CommandError
{
$argName = $commandData->annotationData()->get('validate-migration-id') ?: 'migrationId';
$migrationId = $commandData->input()->getArgument($argName);
if (!$this->migrationPluginManager->hasDefinition($migrationId)) {
return new CommandError(dt('Migration "@id" does not exist', ['@id' => $migrationId]));
}
return null;
}
}