ConnectionFactory.php in Dbal connection 8
File
src/ConnectionFactory.php
View source
<?php
namespace Drupal\dbal;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Driver\Connection;
use Doctrine\DBAL\DriverManager;
use Drupal\Core\Database\Database;
class ConnectionFactory {
protected $info;
protected $cache;
public function __construct() {
$this->info = Database::getAllConnectionInfo();
}
public function __sleep() {
return [
'info',
];
}
public function get($target = 'default') {
if (!isset($this->cache[$target])) {
if (!isset($this->info[$target])) {
$target = 'default';
}
$info = $this->info[$target]['default'];
$options = [
'dbname' => $info['database'],
'user' => $info['username'] ?? '',
'password' => $info['password'] ?? '',
'driver' => 'pdo_' . $info['driver'],
];
if (isset($info['host'])) {
$options['host'] = $info['host'];
}
if (isset($info['unix_socket'])) {
$options['unix_socket'] = $info['unix_socket'];
}
if (isset($info['port'])) {
$options['port'] = $info['port'];
}
$this->cache[$target] = DriverManager::getConnection($options, new Configuration());
if ($info['driver'] == 'sqlite') {
$this
->sqliteDatabases($this->cache[$target], $info['prefix'], $info['database']);
}
}
return $this->cache[$target];
}
protected function sqliteDatabases(Connection $connection, array $prefixes, $base_db) {
$attached = [];
foreach ($prefixes as $prefix) {
if (!isset($attached[$prefix])) {
$attached[$prefix] = TRUE;
$query = $connection
->prepare('ATTACH DATABASE :db AS :prefix');
if ($base_db == ':memory:') {
$query
->execute([
':db' => $base_db,
':prefix' => $prefix,
]);
}
else {
$query
->execute([
':db' => $base_db . '-' . $prefix,
':prefix' => $prefix,
]);
}
}
}
}
}
Classes
Name |
Description |
ConnectionFactory |
Provides a connection factory for connection to databases via doctrine/dbal. |