MySqlConnector::setCustomModes()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 2
c 1
b 0
f 1
nc 1
nop 2
dl 0
loc 5
rs 10
1
<?php
2
3
namespace Nip\Database\Connectors;
4
5
use PDO;
6
7
/**
8
 * Class MySqlConnector
9
 * @package Nip\Database\Connectors
10
 */
11
class MySqlConnector extends Connector
12
{
13
    /**
14
     * Establish a database connection.
15
     *
16
     * @param array $config
17
     * @return \PDO
18
     */
19
    public function connect(array $config)
20
    {
21
        $dsn = $this->getDsn($config);
22
23
        $options = $this->getOptions($config);
24
25
        // We need to grab the PDO options that should be used while making the brand
26
        // new connection instance. The PDO options control various aspects of the
27
        // connection's behavior, and some might be specified by the developers.
28
        $connection = $this->createConnection($dsn, $config, $options);
29
30
        if (!empty($config['database'])) {
31
            $connection->exec("use `{$config['database']}`;");
32
        }
33
34
        $this->configureIsolationLevel($connection, $config);
35
36
        $this->configureEncoding($connection, $config);
37
38
        // Next, we will check to see if a timezone has been specified in this config
39
        // and if it has we will issue a statement to modify the timezone with the
40
        // database. Setting this DB timezone is an optional configuration item.
41
        $this->configureTimezone($connection, $config);
42
43
        $this->setModes($connection, $config);
44
45
        return $connection;
46
    }
47
48
    /**
49
     * Set the connection transaction isolation level.
50
     *
51
     * @param \PDO $connection
52
     * @param array $config
53
     * @return void
54
     */
55
    protected function configureIsolationLevel($connection, array $config)
56
    {
57
        if (!isset($config['isolation_level'])) {
58
            return;
59
        }
60
61
        $connection->prepare(
62
            "SET SESSION TRANSACTION ISOLATION LEVEL {$config['isolation_level']}"
63
        )->execute();
64
    }
65
66
67
    /**
68
     * Set the connection character set and collation.
69
     *
70
     * @param \PDO $connection
71
     * @param array $config
72
     * @return void|\PDO
73
     */
74
    protected function configureEncoding($connection, array $config)
75
    {
76
        if (!isset($config['charset'])) {
77
            return $connection;
78
        }
79
80
        $connection->prepare(
81
            "set names '{$config['charset']}'" . $this->getCollation($config)
82
        )->execute();
83
    }
84
85
    /**
86
     * Get the collation for the configuration.
87
     *
88
     * @param array $config
89
     * @return string
90
     */
91
    protected function getCollation(array $config)
92
    {
93
        return isset($config['collation']) ? " collate '{$config['collation']}'" : '';
94
    }
95
96
    /**
97
     * Set the timezone on the connection.
98
     *
99
     * @param \PDO $connection
100
     * @param array $config
101
     * @return void
102
     */
103
    protected function configureTimezone($connection, array $config)
104
    {
105
        if (isset($config['timezone'])) {
106
            $connection->prepare('set time_zone="' . $config['timezone'] . '"')->execute();
107
        }
108
    }
109
110
    /**
111
     * Create a DSN string from a configuration.
112
     *
113
     * Chooses socket or host/port based on the 'unix_socket' config value.
114
     *
115
     * @param array $config
116
     * @return string
117
     */
118
    protected function getDsn(array $config)
119
    {
120
        return $this->hasSocket($config)
121
            ? $this->getSocketDsn($config)
122
            : $this->getHostDsn($config);
123
    }
124
125
    /**
126
     * Determine if the given configuration array has a UNIX socket value.
127
     *
128
     * @param array $config
129
     * @return bool
130
     */
131
    protected function hasSocket(array $config)
132
    {
133
        return isset($config['unix_socket']) && !empty($config['unix_socket']);
134
    }
135
136
    /**
137
     * Get the DSN string for a socket configuration.
138
     *
139
     * @param array $config
140
     * @return string
141
     */
142
    protected function getSocketDsn(array $config)
143
    {
144
        return "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}";
145
    }
146
147
    /**
148
     * Get the DSN string for a host / port configuration.
149
     *
150
     * @param array $config
151
     * @return string
152
     */
153
    protected function getHostDsn(array $config)
154
    {
155
        extract($config, EXTR_SKIP);
156
157
        return isset($port)
158
            ? "mysql:host={$host};port={$port};dbname={$database}"
159
            : "mysql:host={$host};dbname={$database}";
160
    }
161
162
    /**
163
     * Set the modes for the connection.
164
     *
165
     * @param \PDO $connection
166
     * @param array $config
167
     * @return void
168
     */
169
    protected function setModes(PDO $connection, array $config)
170
    {
171
        if (isset($config['modes'])) {
172
            $this->setCustomModes($connection, $config);
173
        } elseif (isset($config['strict'])) {
174
            if ($config['strict']) {
175
                $connection->prepare($this->strictMode($connection, $config))->execute();
176
            } else {
177
                $connection->prepare("set session sql_mode='NO_ENGINE_SUBSTITUTION'")->execute();
178
            }
179
        }
180
    }
181
182
    /**
183
     * Set the custom modes on the connection.
184
     *
185
     * @param \PDO $connection
186
     * @param array $config
187
     * @return void
188
     */
189
    protected function setCustomModes(PDO $connection, array $config)
190
    {
191
        $modes = implode(',', $config['modes']);
192
193
        $connection->prepare("set session sql_mode='{$modes}'")->execute();
194
    }
195
196
    /**
197
     * Get the query to enable strict mode.
198
     *
199
     * @param \PDO $connection
200
     * @param array $config
201
     * @return string
202
     */
203
    protected function strictMode(PDO $connection, $config)
204
    {
205
        $version = $config['version'] ?? $connection->getAttribute(PDO::ATTR_SERVER_VERSION);
206
207
        if (version_compare($version, '8.0.11') >= 0) {
208
            return "set session sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'";
209
        }
210
211
        return "set session sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'";
212
    }
213
}
214