1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace DrMVC\Database\Drivers; |
4
|
|
|
|
5
|
|
|
use PDO; |
6
|
|
|
use DrMVC\Database\SQLException; |
7
|
|
|
use DrMVC\Database\Drivers\Interfaces\DriverInterface; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Wrapper of PDO for work with MySQL/MariaDB databases |
11
|
|
|
* |
12
|
|
|
* @package DrMVC\Database\Drivers |
13
|
|
|
* @since 3.0 |
14
|
|
|
*/ |
15
|
|
|
class Mysql extends SQL |
16
|
|
|
{ |
17
|
|
|
const DEFAULT_HOST = '127.0.0.1'; |
18
|
|
|
const DEFAULT_PORT = '3306'; |
19
|
|
|
const DEFAULT_CHARSET = 'utf8'; |
20
|
|
|
const DEFAULT_COLLATION = 'utf8_unicode_ci'; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @link https://secure.php.net/manual/en/ref.pdo-mysql.connection.php |
24
|
|
|
* |
25
|
|
|
* The PDO_MYSQL Data Source Name (DSN) is composed of the following elements: |
26
|
|
|
*/ |
27
|
|
|
const AVAILABLE_OPTIONS = [ |
28
|
|
|
'host', |
29
|
|
|
'port', |
30
|
|
|
'dbname', |
31
|
|
|
'unix_socket' |
32
|
|
|
]; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Generate DSN by parameters in config |
36
|
|
|
* |
37
|
|
|
* @param array $config |
38
|
|
|
* @return string |
39
|
|
|
*/ |
40
|
|
|
public function genDsn($config): string |
41
|
|
|
{ |
42
|
|
|
// Parse config |
43
|
|
|
$dsn = ''; |
44
|
|
|
foreach ($config as $key => $value) { |
45
|
|
|
if (\in_array($key, self::AVAILABLE_OPTIONS, false)) { |
46
|
|
|
$dsn .= "$key=$value;"; |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
// Get driver of connection |
51
|
|
|
$driver = strtolower($config['driver']); |
52
|
|
|
|
53
|
|
|
return "$driver:$dsn"; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Initiate connection to database |
58
|
|
|
* |
59
|
|
|
* @return DriverInterface |
60
|
|
|
*/ |
61
|
|
|
public function connect(): DriverInterface |
62
|
|
|
{ |
63
|
|
|
try { |
64
|
|
|
$connection = new PDO( |
65
|
|
|
$this->getDsn(), |
66
|
|
|
$this->getParam('username'), |
67
|
|
|
$this->getParam('password'), |
68
|
|
|
$this->getOptions() |
69
|
|
|
); |
70
|
|
|
$this->setInstance($connection); |
71
|
|
|
|
72
|
|
|
} catch (SQLException $e) { |
73
|
|
|
// __construct |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return $this; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
private function getOptions(): array |
80
|
|
|
{ |
81
|
|
|
// Current charset |
82
|
|
|
$charset = $this->getParam('charset') ?? self::DEFAULT_CHARSET; |
83
|
|
|
|
84
|
|
|
// Current collation |
85
|
|
|
$collation = $this->getParam('collation') ?? self::DEFAULT_COLLATION; |
86
|
|
|
|
87
|
|
|
// Return array of options |
88
|
|
|
return [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES '$charset' COLLATE '$collation'"]; |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
} |
92
|
|
|
|