You are here

protected function Migration::handleDedupe in Migrate 6.2

Same name and namespace in other branches
  1. 7.2 includes/migration.inc \Migration::handleDedupe()

For fields which require uniqueness, assign a new unique value if necessary.

Parameters

array $dedupe: An array with two keys, 'table' the name of the Drupal table and 'column' the column within that table where uniqueness must be maintained.

$original: The value coming in, which must be checked for uniqueness.

Return value

string The value to use - either the original, or a variation created by appending a sequence number.

1 call to Migration::handleDedupe()
Migration::applyMappings in includes/migration.inc
Apply field mappings to a data row received from the source, returning a populated destination object.

File

includes/migration.inc, line 1236
Defines the base class for import/rollback processes.

Class

Migration
The base class for all import objects. This is where most of the smarts of the migrate module resides. Migrations are created by deriving from this class, and in the constructor (after calling parent::__construct()) initializing at a minimum the name,…

Code

protected function handleDedupe($dedupe, $original) {

  // If we're remigrating a previously-existing value, simply running through
  // our normal process will re-dedupe it - we must be sure to preserve the
  // previously-written value. Note that this means that you cannot migrate
  // changes to this field - the originally-migrated value will always
  // remain, because we can't tell what the original was.
  if (isset($this->sourceValues->migrate_map_destid1)) {
    $key_field = key($this->destination
      ->getKeySchema());
    $existing_value = db_select($dedupe['table'], 't')
      ->fields('t', array(
      $dedupe['column'],
    ))
      ->range(0, 1)
      ->condition($key_field, $this->sourceValues->migrate_map_destid1)
      ->execute()
      ->fetchField();

    // Note that if, for some reason, we don't find a value, fall through
    // to the normal deduping process
    if ($existing_value) {
      return $existing_value;
    }
  }
  $i = 1;
  $candidate = $original;
  while ($candidate_found = db_select($dedupe['table'], 't')
    ->fields('t', array(
    $dedupe['column'],
  ))
    ->range(0, 1)
    ->condition($dedupe['column'], $candidate)
    ->execute()
    ->fetchField()) {

    // We already have the candidate value. Find a non-existing value.
    $i++;

    // @TODO: support custom replacement pattern instead of just append.
    $candidate = $original . '_' . $i;
  }
  if ($i > 1) {
    $message = t('Replacing !column !original with !candidate', array(
      '!column' => $dedupe['column'],
      '!original' => $original,
      '!candidate' => $candidate,
    ));
    $migration = Migration::currentMigration();
    $migration
      ->saveMessage($message, Migration::MESSAGE_INFORMATIONAL);
  }
  return $candidate;
}