Completed
Push — master ( 54e54a...70f940 )
by Mr
02:22
created

Mysql::genDsn()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 3
nop 1
1
<?php
2
3
namespace DrMVC\Database\Drivers;
4
5
use DrMVC\Database\SQLException;
6
7
class Mysql extends SQL
8
{
9
    const DEFAULT_HOST = '127.0.0.1';
10
    const DEFAULT_PORT = '3306';
11
    const DEFAULT_CHARSET = 'utf8';
12
    const DEFAULT_COLLATION = 'utf8_unicode_ci';
13
14
    /**
15
     * @link https://secure.php.net/manual/en/ref.pdo-mysql.connection.php
16
     *
17
     * The PDO_MYSQL Data Source Name (DSN) is composed of the following elements:
18
     */
19
    const AVAILABLE_ELEMENTS = [
20
        'host',
21
        'port',
22
        'dbname',
23
        'unix_socket'
24
    ];
25
26
    /**
27
     * Generate DSN by parameters in config
28
     *
29
     * @param   array $config
30
     * @return  string
31
     */
32
    public function genDsn($config): string
33
    {
34
        // Parse config
35
        $dsn = '';
36
        foreach ($config as $key => $value) {
37
            if (\in_array($key, self::AVAILABLE_ELEMENTS, false)) {
38
                $dsn .= "$key=$value;";
39
            }
40
        }
41
        return $dsn;
42
    }
43
44
    /**
45
     * Initiate connection to database
46
     *
47
     * @return  DriverInterface
48
     */
49
    public function connect(): DriverInterface
50
    {
51
        $connection = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $connection is dead and can be removed.
Loading history...
52
        try {
53
            $connection = new \PDO(
54
                $this->getDsn(),
55
                $this->getParam('username'),
56
                $this->getParam('password'),
57
                $this->getOptions()
58
            );
59
        } catch (SQLException $e) {
60
            // __construct
61
        }
62
63
        $this->setConnection($connection);
64
        return $this;
65
    }
66
67
    private function getOptions(): array
68
    {
69
        // Current charset
70
        $charset = $this->getParam('charset') ?? self::DEFAULT_CHARSET;
71
72
        // Current collation
73
        $collation = $this->getParam('collation') ?? self::DEFAULT_COLLATION;
74
75
        // Return array of options
76
        return [\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES '$charset' COLLATE '$collation'"];
77
    }
78
79
}
80