MySqlConnection::getDsn()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
namespace Childish\connection;
3
4
use PDO;
5
use Childish\query\QueryGrammar;
6
7
/**
8
 * MySqlConnection
9
 *
10
 * @author    Pu ShaoWei <[email protected]>
11
 * @date      2017/12/7
12
 * @version   1.0
13
 */
14
class MySqlConnection extends Connection implements ConnectionInterface
15
{
16
    /**
17
     * Get the default query grammar instance.
18
     *
19
     * @return \Childish\query\QueryGrammar
20
     */
21
    protected function getDefaultQueryGrammar()
22
    {
23
        return $this->withTablePrefix(new QueryGrammar);
24
    }
25
26
    /**
27
     * Bind values to their parameters in the given statement.
28
     *
29
     * @param  \PDOStatement $statement
30
     * @param  array         $bindings
31
     * @return void
32
     */
33
    public function bindValues($statement, $bindings)
34
    {
35
        foreach ($bindings as $key => $value) {
36
            $statement->bindValue(
37
                is_string($key) ? $key : $key + 1, $value,
38
                is_int($value) || is_float($value) ? PDO::PARAM_INT : PDO::PARAM_STR
39
            );
40
        }
41
    }
42
43
    /**
44
     * Establish a database connection.
45
     *
46
     * @param  array  $config
47
     * @return \PDO
48
     */
49
    public function connect(array $config)
50
    {
51
        $dsn = $this->getDsn($config);
52
53
        $options = $this->getOptions($config);
0 ignored issues
show
Bug introduced by
The method getOptions() does not seem to exist on object<Childish\connection\MySqlConnection>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
54
55
        // We need to grab the PDO options that should be used while making the brand
56
        // new connection instance. The PDO options control various aspects of the
57
        // connection's behavior, and some might be specified by the developers.
58
        $connection = $this->createConnection($dsn, $config, $options);
0 ignored issues
show
Bug introduced by
The method createConnection() does not exist on Childish\connection\MySqlConnection. Did you maybe mean connect()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
59
60
        if (! empty($config['database'])) {
61
            $connection->exec("use `{$config['database']}`;");
62
        }
63
64
        $this->configureEncoding($connection, $config);
65
66
        // Next, we will check to see if a timezone has been specified in this config
67
        // and if it has we will issue a statement to modify the timezone with the
68
        // database. Setting this DB timezone is an optional configuration item.
69
        $this->configureTimezone($connection, $config);
70
71
        $this->setModes($connection, $config);
72
73
        return $connection;
74
    }
75
76
    /**
77
     * Set the connection character set and collation.
78
     *
79
     * @param  \PDO  $connection
80
     * @param  array  $config
81
     * @return void
82
     */
83
    protected function configureEncoding($connection, array $config)
84
    {
85
        if (! isset($config['charset'])) {
86
            return $connection;
87
        }
88
89
        $connection->prepare(
90
            "set names '{$config['charset']}'".$this->getCollation($config)
91
        )->execute();
92
    }
93
94
    /**
95
     * Get the collation for the configuration.
96
     *
97
     * @param  array  $config
98
     * @return string
99
     */
100
    protected function getCollation(array $config)
101
    {
102
        return isset($config['collation']) ? " collate '{$config['collation']}'" : '';
103
    }
104
105
    /**
106
     * Set the timezone on the connection.
107
     *
108
     * @param  \PDO  $connection
109
     * @param  array  $config
110
     * @return void
111
     */
112
    protected function configureTimezone($connection, array $config)
113
    {
114
        if (isset($config['timezone'])) {
115
            $connection->prepare('set time_zone="'.$config['timezone'].'"')->execute();
116
        }
117
    }
118
119
    /**
120
     * Create a DSN string from a configuration.
121
     *
122
     * Chooses socket or host/port based on the 'unix_socket' config value.
123
     *
124
     * @param  array   $config
125
     * @return string
126
     */
127
    protected function getDsn(array $config)
128
    {
129
        return $this->hasSocket($config)
130
            ? $this->getSocketDsn($config)
131
            : $this->getHostDsn($config);
132
    }
133
134
    /**
135
     * Determine if the given configuration array has a UNIX socket value.
136
     *
137
     * @param  array  $config
138
     * @return bool
139
     */
140
    protected function hasSocket(array $config)
141
    {
142
        return isset($config['unix_socket']) && ! empty($config['unix_socket']);
143
    }
144
145
    /**
146
     * Get the DSN string for a socket configuration.
147
     *
148
     * @param  array  $config
149
     * @return string
150
     */
151
    protected function getSocketDsn(array $config)
152
    {
153
        return "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}";
154
    }
155
156
    /**
157
     * Get the DSN string for a host / port configuration.
158
     *
159
     * @param  array  $config
160
     * @return string
161
     */
162
    protected function getHostDsn(array $config)
163
    {
164
        extract($config, EXTR_SKIP);
165
166
        return isset($port)
167
            ? "mysql:host={$host};port={$port};dbname={$database}"
168
            : "mysql:host={$host};dbname={$database}";
169
    }
170
171
    /**
172
     * Set the modes for the connection.
173
     *
174
     * @param  \PDO  $connection
175
     * @param  array  $config
176
     * @return void
177
     */
178
    protected function setModes(PDO $connection, array $config)
179
    {
180
        if (isset($config['modes'])) {
181
            $this->setCustomModes($connection, $config);
182
        } elseif (isset($config['strict'])) {
183
            if ($config['strict']) {
184
                $connection->prepare($this->strictMode())->execute();
185
            } else {
186
                $connection->prepare("set session sql_mode='NO_ENGINE_SUBSTITUTION'")->execute();
187
            }
188
        }
189
    }
190
191
    /**
192
     * Set the custom modes on the connection.
193
     *
194
     * @param  \PDO  $connection
195
     * @param  array  $config
196
     * @return void
197
     */
198
    protected function setCustomModes(PDO $connection, array $config)
199
    {
200
        $modes = implode(',', $config['modes']);
201
202
        $connection->prepare("set session sql_mode='{$modes}'")->execute();
203
    }
204
205
    /**
206
     * Get the query to enable strict mode.
207
     *
208
     * @return string
209
     */
210
    protected function strictMode()
211
    {
212
        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'";
213
    }
214
}