Skip to content

Instantly share code, notes, and snippets.

@mohit-rocks
Created February 14, 2018 03:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohit-rocks/be98377c6d70ccf22e6933a0557746cb to your computer and use it in GitHub Desktop.
Save mohit-rocks/be98377c6d70ccf22e6933a0557746cb to your computer and use it in GitHub Desktop.
ID Map plugin for migration (Drupal 8)
<?php
namespace Drupal\my_module\Plugin\migrate\id_map;
use Drupal\migrate\MigrateException;
use Drupal\migrate\Plugin\migrate\id_map\Sql;
/**
* Defines the sql based ID map implementation.
*
* It creates one map and one message table per migration entity to store the
* relevant information.
*
* @PluginID("content_update")
*/
class ContentUpdate extends Sql {
/**
* {@inheritdoc}
*/
public function lookupDestinationId(array $source_id_values) {
$results = $this->lookupDestinationIds($source_id_values);
return $results;
}
/**
* {@inheritdoc}
*/
public function lookupDestinationIds(array $source_id_values) {
if (empty($source_id_values)) {
return [];
}
$source_ids = $source_id_values;
// Now check if there are any existing nodes with same product unique IDs.
if (isset($source_ids['Item-ID'])) {
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
'field_page_unique_id' => $source_ids['Item-ID'],
]);
if ($nodes !== NULL) {
return array_keys($nodes);
}
}
// Canonicalize the keys into a hash of DB-field => value.
$is_associative = !isset($source_id_values[0]);
$conditions = [];
foreach ($this->sourceIdFields() as $field_name => $db_field) {
if ($is_associative) {
// Associative $source_id_values can have fields out of order.
if (isset($source_id_values[$field_name])) {
$conditions[$db_field] = $source_id_values[$field_name];
unset($source_id_values[$field_name]);
}
}
else {
// For non-associative $source_id_values, we assume they're the first
// few fields.
if (empty($source_id_values)) {
break;
}
$conditions[$db_field] = array_shift($source_id_values);
}
}
if (!empty($source_id_values)) {
throw new MigrateException("Extra unknown items in source IDs");
}
$query = $this->getDatabase()->select($this->mapTableName(), 'map')
->fields('map', $this->destinationIdFields());
if (count($this->sourceIdFields()) === count($conditions)) {
// Optimization: Use the primary key.
$query->condition(self::SOURCE_IDS_HASH, $this->getSourceIDsHash(array_values($conditions)));
}
else {
foreach ($conditions as $db_field => $value) {
$query->condition($db_field, $value);
}
}
$migrated_source_ids = $query->execute()->fetchAll(\PDO::FETCH_NUM);
if (!empty($migrated_source_ids)) {
return $migrated_source_ids;
}
return [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment