MySqlConnectionProvider   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 46
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getOptions() 0 7 1
A __construct() 0 3 1
A getDataSourceName() 0 13 3
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