|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Willry\QueryBuilder; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* Class Connect Singleton Pattern |
|
7
|
|
|
*/ |
|
8
|
|
|
class Connect |
|
9
|
|
|
{ |
|
10
|
|
|
|
|
11
|
|
|
/** @var array */ |
|
12
|
|
|
private static $instance; |
|
13
|
|
|
|
|
14
|
|
|
/** @var \Exception|null */ |
|
15
|
|
|
private static $error = null; |
|
16
|
|
|
|
|
17
|
|
|
private static $configurations = []; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Connect constructor. Private singleton |
|
21
|
|
|
*/ |
|
22
|
|
|
private function __construct() |
|
23
|
|
|
{ |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Connect clone. Private singleton |
|
28
|
|
|
*/ |
|
29
|
|
|
private function __clone() |
|
30
|
|
|
{ |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public static function getInstance($dbName = null, $regenerateConnection = false): ?\PDO |
|
34
|
|
|
{ |
|
35
|
|
|
$configurations = self::$configurations ?? []; |
|
36
|
|
|
$default = reset($configurations); |
|
37
|
|
|
|
|
38
|
|
|
$dbConf = $configurations[$dbName] ?? $default; |
|
39
|
|
|
|
|
40
|
|
|
$dbDsn = $dbConf["driver"] . ":host=" . $dbConf["host"] . ";dbname=" . $dbConf["dbname"] . ";port=" . $dbConf["port"]; |
|
41
|
|
|
|
|
42
|
|
|
//DSN alternative for SQL Server (sqlsrv) |
|
43
|
|
|
if ($dbConf['driver'] == 'sqlsrv') { |
|
44
|
|
|
$dbDsn = $dbConf["driver"] . ":Server=" . $dbConf["host"] . "," . $dbConf["port"] . ";Database=" . $dbConf["dbname"]; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
if (empty(self::$instance[$dbName]) || $regenerateConnection) { |
|
48
|
|
|
try { |
|
49
|
|
|
self::$instance[$dbName] = new \PDO( |
|
50
|
|
|
$dbDsn, |
|
51
|
|
|
$dbConf["username"], |
|
52
|
|
|
$dbConf["passwd"], |
|
53
|
|
|
$dbConf["options"] |
|
54
|
|
|
); |
|
55
|
|
|
} catch (\PDOException $exception) { |
|
56
|
|
|
self::$error = $exception; |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
return self::$instance[$dbName]; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* @return \Exception|null |
|
65
|
|
|
*/ |
|
66
|
|
|
public static function getError(): ?\Exception |
|
67
|
|
|
{ |
|
68
|
|
|
return self::$error; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
public static function config(array $configurations) |
|
72
|
|
|
{ |
|
73
|
|
|
self::$configurations = $configurations; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
public static function getConfig(string $connectionName): ?array |
|
77
|
|
|
{ |
|
78
|
|
|
return self::$configurations[$connectionName] ?? null; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|