1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Simply\Database\Connection\Provider; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Basic connection provider for MySQL databases. |
7
|
|
|
* @author Riikka Kalliomäki <[email protected]> |
8
|
|
|
* @copyright Copyright (c) 2018 Riikka Kalliomäki |
9
|
|
|
* @license http://opensource.org/licenses/mit-license.php MIT License |
10
|
|
|
*/ |
11
|
|
|
class MySqlConnectionProvider extends GenericConnectionProvider |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* MySqlConnectionProvider constructor. |
15
|
|
|
* @param string $hostname The hostname for the database with optional port or path to unix socket |
16
|
|
|
* @param string $database The name of the database to connect |
17
|
|
|
* @param string $username The username used for the connection |
18
|
|
|
* @param string $password The password for the username or empty string for none |
19
|
|
|
*/ |
20
|
25 |
|
public function __construct(string $hostname, string $database, string $username, string $password) |
21
|
|
|
{ |
22
|
25 |
|
parent::__construct($this->getDataSourceName($hostname, $database), $username, $password, $this->getOptions()); |
23
|
25 |
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Returns the data source name based on the hostname and the database. |
27
|
|
|
* @param string $hostname The hostname for the connection |
28
|
|
|
* @param string $database The database for the connection |
29
|
|
|
* @return string The data source name string for the connection |
30
|
|
|
*/ |
31
|
25 |
|
protected function getDataSourceName(string $hostname, string $database): string |
32
|
|
|
{ |
33
|
25 |
|
if (strncmp($hostname, '/', 1) === 0) { |
34
|
1 |
|
return sprintf('mysql:unix_socket=%s;dbname=%s;charset=utf8mb4', $hostname, $database); |
35
|
|
|
} |
36
|
|
|
|
37
|
25 |
|
$parts = explode(':', $hostname, 2); |
38
|
|
|
|
39
|
25 |
|
if (\count($parts) === 1) { |
40
|
25 |
|
return sprintf('mysql:host=%s;dbname=%s;charset=utf8mb4', $hostname, $database); |
41
|
|
|
} |
42
|
|
|
|
43
|
1 |
|
return sprintf('mysql:host=%s;port=%d;dbname=%s;charset=utf8mb4', $parts[0], $parts[1], $database); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Returns the default PDO options to use for the connection. |
48
|
|
|
* @return array The default PDO options to use for the connection |
49
|
|
|
*/ |
50
|
25 |
|
protected function getOptions(): array |
51
|
|
|
{ |
52
|
|
|
return [ |
53
|
25 |
|
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, |
54
|
|
|
\PDO::ATTR_EMULATE_PREPARES => false, |
55
|
25 |
|
\PDO::MYSQL_ATTR_INIT_COMMAND => sprintf("SET time_zone = '%s'", date('P')), |
56
|
|
|
\PDO::MYSQL_ATTR_FOUND_ROWS => true, |
57
|
|
|
]; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|