Skip to content

Instantly share code, notes, and snippets.

@vladdancer
Created June 21, 2022 09:53
Show Gist options
  • Save vladdancer/56e4616698f9ae6e43ae8777e0180328 to your computer and use it in GitHub Desktop.
Save vladdancer/56e4616698f9ae6e43ae8777e0180328 to your computer and use it in GitHub Desktop.
Include database connection information from not native connection file #drupal8+
<?php
$legacy_db_key = 'project_legacy_db';
// Define database connection for local lando env.
if (getenv('LANDO_INFO')) {
$lando_info = json_decode(getenv('LANDO_INFO'), TRUE);
$databases[$legacy_db_key]['default'] = [
'database' => 'project_legacy',
'username' => $lando_info['database']['creds']['user'],
'password' => $lando_info['database']['creds']['password'],
'prefix' => '',
'host' => $lando_info['database']['internal_connection']['host'],
'port' => $lando_info['database']['internal_connection']['port'],
'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
'driver' => 'mysql',
];
}
else {
// Otherwise, get connection info from legacy production db.
$extraDatabases = [
'default' => [
'default' => [],
],
];
$code = @file_get_contents('/var/www/site-php/project.prod/D9-prod-settings.inc');
if (empty($code)) {
return;
}
$code = str_replace('<?php', '', $code);
// Rename $databases variable into $extraDatabases,
// to avoid overriding default $databases variable.
$code = str_replace('databases', 'extraDatabases', $code);
// Comment out code imports, since we need only array with connection info.
$code = str_replace('require', '//', $code);
$code = str_replace('include', '//', $code);
try {
eval($code);
}
catch (\ParseError $exception) {}
if (!empty($extraDatabases['default']['default'])) {
$databases[$legacy_db_key]['default'] = $extraDatabases['default']['default'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment