MediaMigrationTestDatabaseTrait.php in Media Migration 8
File
tests/src/Traits/MediaMigrationTestDatabaseTrait.php
View source
<?php
namespace Drupal\Tests\media_migration\Traits;
use Drupal\Core\Database\Database;
trait MediaMigrationTestDatabaseTrait {
protected function createSourceMigrationConnection() {
if (Database::getConnectionInfo('simpletest_original_migrate')) {
throw new \RuntimeException("Bad Database connection state: 'simpletest_original_migrate' connection key already exists. Broken test?");
}
$connection_info = Database::getConnectionInfo('migrate');
if ($connection_info) {
Database::renameConnection('migrate', 'simpletest_original_migrate');
}
$connection_info = Database::getConnectionInfo('default');
foreach ($connection_info as $target => $value) {
$prefix = is_array($value['prefix']) ? $value['prefix']['default'] : $value['prefix'];
$connection_info[$target]['prefix']['default'] = $prefix . '0';
$connection_info[$target]['prefix'][$value['prefix']['default']] = $value['prefix']['default'];
}
Database::addConnectionInfo('migrate', 'default', $connection_info['default']);
}
protected function importSourceDatabase(array $database) : void {
foreach ($database as $table => $rows) {
$counts = array_map('count', $rows);
asort($counts);
end($counts);
$pilot = $rows[key($counts)];
$schema = array_map(function ($value) {
$type = is_numeric($value) && !is_float($value + 0) ? 'int' : 'text';
return [
'type' => $type,
];
}, $pilot);
$this->sourceDatabase
->schema()
->createTable($table, [
'fields' => $schema,
]);
$fields = array_keys($pilot);
$insert = $this->sourceDatabase
->insert($table)
->fields($fields);
array_walk($rows, [
$insert,
'values',
]);
$insert
->execute();
}
}
private function cleanupSourceMigrateConnection() {
Database::removeConnection('migrate');
$original_connection_info = Database::getConnectionInfo('simpletest_original_migrate');
if ($original_connection_info) {
Database::renameConnection('simpletest_original_migrate', 'migrate');
}
}
}