IdPostRowSave.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Drupal\reinstall\EventSubscriber;
  3. use Drupal\Component\Utility\NestedArray;
  4. use Drupal\migrate\Event\MigrateEvents;
  5. use Drupal\migrate\Event\MigratePostRowSaveEvent;
  6. use Drupal\migrate\Row;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. /**
  9. * Class IdPostRowSave normalizes ids after the destination saved the row.
  10. *
  11. * This is needed because raw reinstall sources do not flatten source values,
  12. * and Sql::saveIdMap() assumes property fields are scalars of the described
  13. * type for the source, so we need to overwrite the source value for this last
  14. * step.
  15. *
  16. * Example: a node has an integer "nid" key, but is dumped like:
  17. * <nid>:
  18. * nid:
  19. * -
  20. * value: 2
  21. * ...
  22. */
  23. class IdPostRowSave implements EventSubscriberInterface {
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public static function getSubscribedEvents() {
  28. $events = [
  29. MigrateEvents::POST_ROW_SAVE => 'postRowSave',
  30. ];
  31. return $events;
  32. }
  33. /**
  34. * Callback for POST_ROW_SAVE.
  35. *
  36. * @param \Drupal\migrate\Event\MigratePostRowSaveEvent $event
  37. * The event instance.
  38. */
  39. public function postRowSave(MigratePostRowSaveEvent $event) {
  40. $row = $event->getRow();
  41. $idValues = $row->getSourceIdValues();
  42. foreach ($idValues as $idName => $idValue) {
  43. $current = $idValue;
  44. while (is_array($current)) {
  45. $current = current($current);
  46. }
  47. // Unavailable because source is frozen at this point.
  48. // $row->setSourceProperty($idName, $current);
  49. // So let's use brute force.
  50. NestedArray::setValue($row->getSource(), explode(Row::PROPERTY_SEPARATOR, $idName), $current, TRUE);
  51. }
  52. }
  53. }