function MigrateSqlSourceTestBase::getDatabase

Same name in other branches
  1. 9 core/modules/migrate/tests/src/Kernel/MigrateSqlSourceTestBase.php \Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase::getDatabase()
  2. 8.9.x core/modules/migrate/tests/src/Kernel/MigrateSqlSourceTestBase.php \Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase::getDatabase()
  3. 11.x core/modules/migrate/tests/src/Kernel/MigrateSqlSourceTestBase.php \Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase::getDatabase()

Builds an in-memory SQLite database from a set of source data.

Parameters

array $source_data: The source data, keyed by table name. Each table is an array containing the rows in that table.

Return value

\Drupal\sqlite\Driver\Database\sqlite\Connection The SQLite database connection.

1 call to MigrateSqlSourceTestBase::getDatabase()
MigrateSqlSourceTestBase::testSource in core/modules/migrate/tests/src/Kernel/MigrateSqlSourceTestBase.php
Tests the source plugin against a particular data set.

File

core/modules/migrate/tests/src/Kernel/MigrateSqlSourceTestBase.php, line 37

Class

MigrateSqlSourceTestBase
Base class for tests of Migrate source plugins that use a database.

Namespace

Drupal\Tests\migrate\Kernel

Code

protected function getDatabase(array $source_data) {
    // Create an in-memory SQLite database. Plugins can interact with it like
    // any other database, and it will cease to exist when the connection is
    // closed.
    $connection_options = [
        'database' => ':memory:',
    ];
    $pdo = Connection::open($connection_options);
    $connection = new Connection($pdo, $connection_options);
    // Create the tables and fill them with data.
    foreach ($source_data as $table => $rows) {
        // Use the biggest row to build the table schema.
        $counts = array_map('count', $rows);
        asort($counts);
        $pilot = $rows[array_key_last($counts)];
        $connection->schema()
            ->createTable($table, [
            // SQLite uses loose affinity typing, so it's OK for every field to
            // be a text field.
'fields' => array_map(function () {
                return [
                    'type' => 'text',
                ];
            }, $pilot),
        ]);
        $fields = array_keys($pilot);
        $insert = $connection->insert($table)
            ->fields($fields);
        array_walk($rows, [
            $insert,
            'values',
        ]);
        $insert->execute();
    }
    return $connection;
}

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