function Sql::getHighestId

Same name in other branches
  1. 9 core/modules/migrate/src/Plugin/migrate/id_map/Sql.php \Drupal\migrate\Plugin\migrate\id_map\Sql::getHighestId()
  2. 8.9.x core/modules/migrate/src/Plugin/migrate/id_map/Sql.php \Drupal\migrate\Plugin\migrate\id_map\Sql::getHighestId()
  3. 10 core/modules/migrate/src/Plugin/migrate/id_map/Sql.php \Drupal\migrate\Plugin\migrate\id_map\Sql::getHighestId()

Overrides HighestIdInterface::getHighestId

File

core/modules/migrate/src/Plugin/migrate/id_map/Sql.php, line 1012

Class

Sql
Defines the sql based ID map implementation.

Namespace

Drupal\migrate\Plugin\migrate\id_map

Code

public function getHighestId() {
    // Ensure that the first ID is an integer.
    $keys = $this->migration
        ->getDestinationPlugin()
        ->getIds();
    if (reset($keys)['type'] !== 'integer') {
        throw new \LogicException('To determine the highest migrated ID the first ID must be an integer');
    }
    // List of mapping tables to look in for the highest ID.
    $map_tables = [
        $this->migration
            ->id() => $this->mapTableName(),
    ];
    // If there's a bundle, it means we have a derived migration and we need to
    // find all the mapping tables from the related derived migrations.
    if ($base_id = substr($this->migration
        ->id(), 0, strpos($this->migration
        ->id(), $this::DERIVATIVE_SEPARATOR))) {
        $migrations = $this->migrationPluginManager
            ->getDefinitions();
        foreach ($migrations as $migration_id => $migration) {
            if ($migration['id'] === $base_id) {
                // Get this derived migration's mapping table and add it to the list
                // of mapping tables to look in for the highest ID.
                $stub = $this->migrationPluginManager
                    ->createInstance($migration_id);
                $map_tables[$migration_id] = $stub->getIdMap()
                    ->mapTableName();
            }
        }
    }
    // Get the highest id from the list of map tables.
    $ids = [
        0,
    ];
    foreach ($map_tables as $map_table) {
        // If the map_table does not exist then continue on to the next map_table.
        if (!$this->getDatabase()
            ->schema()
            ->tableExists($map_table)) {
            continue;
        }
        $query = $this->getDatabase()
            ->select($map_table, 'map')
            ->fields('map', $this->destinationIdFields())
            ->range(0, 1);
        foreach (array_values($this->destinationIdFields()) as $order_field) {
            $query->orderBy($order_field, 'DESC');
        }
        $ids[] = $query->execute()
            ->fetchField();
    }
    // Return the highest of all the mapped IDs.
    return (int) max($ids);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.