1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @author Rémy M. Böhler <[email protected]> |
4
|
|
|
*/ |
5
|
|
|
declare(strict_types=1); |
6
|
|
|
|
7
|
|
|
namespace Rorm; |
8
|
|
|
|
9
|
|
|
use PDO; |
10
|
|
|
|
11
|
|
|
class Rorm |
12
|
|
|
{ |
13
|
|
|
const CONNECTION_DEFAULT = 'default'; |
14
|
|
|
|
15
|
|
|
/** @var PDO[] */ |
16
|
|
|
protected static $connections; |
17
|
|
|
|
18
|
2 |
|
public static function setDatabase(PDO $dbh, string $connection = self::CONNECTION_DEFAULT): void |
19
|
|
|
{ |
20
|
2 |
|
static::$connections[$connection] = $dbh; |
21
|
2 |
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @throws ConnectionNotFoundException |
25
|
|
|
*/ |
26
|
3 |
|
public static function getDatabase(string $connection = self::CONNECTION_DEFAULT): PDO |
27
|
|
|
{ |
28
|
3 |
|
if (array_key_exists($connection, static::$connections)) { |
29
|
2 |
|
return static::$connections[$connection]; |
30
|
|
|
} |
31
|
|
|
|
32
|
1 |
|
throw new ConnectionNotFoundException('Database connection not found!'); |
33
|
|
|
} |
34
|
|
|
|
35
|
1 |
|
public static function isMySQL(PDO $dbh): bool |
36
|
|
|
{ |
37
|
1 |
|
return $dbh->getAttribute(PDO::ATTR_DRIVER_NAME) === 'mysql'; |
38
|
|
|
} |
39
|
|
|
|
40
|
1 |
|
public static function isSQLite(PDO $dbh): bool |
41
|
|
|
{ |
42
|
1 |
|
return $dbh->getAttribute(PDO::ATTR_DRIVER_NAME) === 'sqlite'; |
43
|
|
|
} |
44
|
|
|
|
45
|
3 |
|
public static function quote(PDO $dbh, $value) |
46
|
|
|
{ |
47
|
3 |
|
if (is_bool($value)) { |
48
|
|
|
/** |
49
|
|
|
* MySQL has true and false literals |
50
|
|
|
* SQLite does not support boolean type nor literals |
51
|
|
|
*/ |
52
|
2 |
|
if (static::isMySQL($dbh)) { |
53
|
1 |
|
return $value ? 'TRUE' : 'FALSE'; |
54
|
|
|
} else { |
55
|
1 |
|
return $value ? 1 : 0; |
56
|
|
|
} |
57
|
|
|
} |
58
|
1 |
|
if ($value === null) { |
59
|
1 |
|
return 'NULL'; |
60
|
|
|
} |
61
|
1 |
|
if (is_int($value)) { |
62
|
1 |
|
return (int)$value; |
63
|
|
|
} |
64
|
1 |
|
if (is_float($value)) { |
65
|
1 |
|
return (float)$value; |
66
|
|
|
} |
67
|
|
|
|
68
|
1 |
|
return $dbh->quote($value); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Method to quote identifiers |
73
|
|
|
* Please make sure you keep the quoter as long you are needing it. |
74
|
|
|
*/ |
75
|
8 |
|
public static function getIdentifierQuoter(PDO $dbh = null): ?callable |
76
|
|
|
{ |
77
|
8 |
|
$dbh = $dbh ?: static::getDatabase(); |
78
|
|
|
|
79
|
8 |
|
if (static::isMySQL($dbh)) { |
80
|
|
|
// mysql mode |
81
|
4 |
|
return function ($identifier) { |
82
|
4 |
|
return '`' . str_replace('`', '``', $identifier) . '`'; |
83
|
4 |
|
}; |
84
|
|
|
} else { |
85
|
|
|
// standard sql mode |
86
|
4 |
|
return function ($identifier) { |
87
|
4 |
|
return '"' . str_replace('"', '""', $identifier) . '"'; |
88
|
4 |
|
}; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|
92
|
1 |
|
public static function reset() |
93
|
|
|
{ |
94
|
1 |
|
static::$connections = []; |
95
|
1 |
|
} |
96
|
|
|
} |
97
|
|
|
|