forked from php-censor/php-censor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseManager.php
More file actions
98 lines (78 loc) · 2.94 KB
/
Copy pathDatabaseManager.php
File metadata and controls
98 lines (78 loc) · 2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
declare(strict_types=1);
namespace PHPCensor;
use PHPCensor\Common\Exception\Exception;
use PHPCensor\Common\Exception\RuntimeException;
use PHPCensor\Common\Application\ConfigurationInterface;
/**
* @package PHP Censor
* @subpackage Application
*
* @author Dmitry Khomutov <poisoncorpsee@gmail.com>
*/
class DatabaseManager
{
public const MYSQL_TYPE = 'mysql';
public const POSTGRESQL_TYPE = 'pgsql';
private ConfigurationInterface $configuration;
private array $connections = [
'read' => null,
'write' => null
];
public function __construct(ConfigurationInterface $configuration)
{
$this->configuration = $configuration;
}
/**
* @throws Exception
*/
public function getConnection(string $type = 'read'): DatabaseConnection
{
if (null === $this->connections[$type]) {
$servers = (array)$this->configuration->get("php-censor.database.servers.{$type}", []);
\shuffle($servers);
$connection = null;
while (\count($servers)) {
$server = \array_shift($servers);
$driver = $this->configuration->get('php-censor.database.type', self::POSTGRESQL_TYPE);
$dsn = $driver . ':host=' . $server['host'];
if (self::POSTGRESQL_TYPE === $driver) {
if (!\array_key_exists('pgsql-sslmode', $server)) {
$server['pgsql-sslmode'] = 'prefer';
}
$dsn .= ';sslmode=' . $server['pgsql-sslmode'];
}
if (isset($server['port'])) {
$dsn .= ';port=' . (int)$server['port'];
}
$dsn .= ';dbname=' . $this->configuration->get('php-censor.database.name', '');
$pdoOptions = [
\PDO::ATTR_PERSISTENT => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_TIMEOUT => 2,
];
if (self::MYSQL_TYPE === $driver) {
$pdoOptions[\PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES 'UTF8'";
}
try {
$connection = new DatabaseConnection(
$dsn,
$this->configuration->get('php-censor.database.username', ''),
$this->configuration->get('php-censor.database.password', ''),
$pdoOptions
);
} catch (\PDOException $ex) {
$connection = false;
}
if ($connection) {
break;
}
}
if (!$connection) {
throw new RuntimeException('Could not connect to any ' . $type . ' servers.');
}
$this->connections[$type] = $connection;
}
return $this->connections[$type];
}
}