Completed
Push — master ( aaac57...e2ab3e )
by Oleg
05:20
created

MysqlDriver   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 286
Duplicated Lines 7.69 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 32
c 4
b 0
f 0
lcom 1
cbo 1
dl 22
loc 286
rs 9.6

13 Methods

Rating   Name   Duplication   Size   Complexity  
A switchDatabase() 0 4 1
A infoDatabase() 0 18 2
A listDatabases() 0 17 3
A listTables() 0 4 1
A createTable() 0 6 1
A removeTable() 0 4 1
A listFields() 0 18 2
A fieldInfo() 0 8 2
C insert() 22 22 8
A update() 0 19 4
A delete() 0 4 1
A count() 0 15 4
A exists() 0 14 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php /** MysqlDriverMicro */
2
3
namespace Micro\Db\Drivers;
4
5
/**
6
 * MySQL Driver class file.
7
 *
8
 * @author Oleg Lunegov <[email protected]>
9
 * @link https://github.com/linpax/microphp-framework
10
 * @copyright Copyright (c) 2013 Oleg Lunegov
11
 * @license https://github.com/linpax/microphp-framework/blob/master/LICENSE
12
 * @package Micro
13
 * @subpackage Db\Drivers
14
 * @version 1.0
15
 * @since 1.0
16
 */
17
class MysqlDriver extends Driver
18
{
19
    /**
20
     * Set current database
21
     *
22
     * @access public
23
     *
24
     * @param string $dbName Database name
25
     *
26
     * @return boolean
27
     */
28
    public function switchDatabase($dbName)
29
    {
30
        return $this->conn->exec("USE {$dbName};") !== false;
31
    }
32
33
    /**
34
     * Info of database
35
     *
36
     * @access public
37
     * @param string $dbName Database name
38
     * @return array
39
     */
40
    public function infoDatabase($dbName)
41
    {
42
        $sth = $this->conn->query("SHOW TABLE STATUS FROM {$dbName};");
43
44
        $result = [];
45
        foreach ($sth->fetchAll() AS $row) {
46
            $result[] = [
47
                'name' => $row['Name'],
48
                'engine' => $row['Engine'],
49
                'rows' => $row['Rows'],
50
                'length' => $row['Avg_row_length'],
51
                'increment' => $row['Auto_increment'],
52
                'collation' => $row['Collation']
53
            ];
54
        }
55
56
        return $result;
57
    }
58
59
    /**
60
     * List database names on this connection
61
     *
62
     * @access public
63
     * @return array
64
     */
65
    public function listDatabases()
66
    {
67
        $sql = 'SHOW DATABASES;';
68
69
        if ($this->getDriverType() === 'pgsql') {
70
            $sql = 'SELECT datname FROM pg_database;';
71
        }
72
73
        $sth = $this->conn->query($sql);
74
        $result = [];
75
76
        foreach ($sth->fetchAll() AS $row) {
77
            $result[] = $row[0];
78
        }
79
80
        return $result;
81
    }
82
83
    /**
84
     * List tables in db
85
     *
86
     * @access public
87
     * @return array
88
     */
89
    public function listTables()
90
    {
91
        return $this->conn->query('SHOW TABLES;')->fetchAll(\PDO::FETCH_COLUMN, 0);
92
    }
93
94
    /**
95
     * Create a new table
96
     *
97
     * @param string $name Table name
98
     * @param array $elements Table elements
99
     * @param string $params Table params
100
     *
101
     * @return int
102
     */
103
    public function createTable($name, array $elements = [], $params = '')
104
    {
105
        return $this->conn->exec(
106
            sprintf('SELECT TABLE IF NOT EXISTS `%s` (%s) %s;', $name, implode(', ', $elements), $params)
107
        );
108
    }
109
110
    /**
111
     * Remove table from database
112
     *
113
     * @access public
114
     *
115
     * @param string $name Table name
116
     *
117
     * @return mixed
118
     */
119
    public function removeTable($name)
120
    {
121
        return $this->conn->exec("DROP TABLE {$name};");
122
    }
123
124
    /**
125
     * Get array fields into table
126
     *
127
     * @access public
128
     *
129
     * @param string $table Table name
130
     *
131
     * @return array
132
     */
133
    public function listFields($table)
134
    {
135
        $sth = $this->conn->query("SHOW COLUMNS FROM {$table};");
136
137
        $result = [];
138
        foreach ($sth->fetchAll(\PDO::FETCH_ASSOC) as $row) {
139
            $result[] = [
140
                'field' => $row['Field'],
141
                'type' => $row['Type'],
142
                'null' => $row['Null'],
143
                'key' => $row['Key'],
144
                'default' => $row['Default'],
145
                'extra' => $row['Extra']
146
            ];
147
        }
148
149
        return $result;
150
    }
151
152
    /**
153
     * Get info of a field
154
     *
155
     * @access public
156
     *
157
     * @param string $field Field name
158
     * @param string $table Table name
159
     *
160
     * @return array|boolean
161
     */
162
    public function fieldInfo($field, $table)
163
    {
164
        if ($this->fieldExists($field, $table)) {
165
            return $this->conn->query("SELECT {$field} FROM {$table} LIMIT 1;")->getColumnMeta(0);
166
        }
167
168
        return false;
169
    }
170
171
    /**
172
     * Insert row into table
173
     *
174
     * @access public
175
     *
176
     * @param string $table Table name
177
     * @param array $line Line or lines to added
178
     * @param bool $multi Is multi rows
179
     *
180
     * @return bool
181
     */
182 View Code Duplication
    public function insert($table, array $line = [], $multi = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
183
    {
184
        $fields = '`' . implode('`, `', array_keys($multi ? $line[0] : $line)) . '`';
185
186
        $values = ':'.implode(', :', array_keys($multi ? $line[0] : $line));
187
        $rows = $multi ? $line : [$line];
188
        $id = null;
189
190
        if ($rows) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $rows of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
191
            $this->conn->beginTransaction();
192
193
            $dbh = null;
194
            foreach ($rows AS $row) {
195
                $dbh = $this->conn->prepare("INSERT INTO {$table} ({$fields}) VALUES ({$values});")->execute($row);
196
            }
197
198
            $id = $dbh ? $this->conn->lastInsertId() : false;
199
            $this->conn->commit();
200
        }
201
202
        return $id ?: false;
203
    }
204
205
    /**
206
     * Update row in table
207
     *
208
     * @access public
209
     *
210
     * @param string $table Table name
211
     * @param array $elements Elements to update
212
     * @param string $conditions Conditions for search
213
     *
214
     * @return bool
215
     */
216
    public function update($table, array $elements = [], $conditions = '')
217
    {
218
        $keys = array_keys($elements);
219
        if (0 === count($keys)) {
220
            return false;
221
        }
222
223
        $valStr = [];
224
        foreach ($keys as $key) {
225
            $valStr[] = '`'.$key.'` = :'.$key;
226
        }
227
        $valStr = implode(',', $valStr);
228
229
        if ($conditions) {
230
            $conditions = 'WHERE '.$conditions;
231
        }
232
233
        return $this->conn->prepare("UPDATE {$table} SET {$valStr} {$conditions};")->execute($elements);
234
    }
235
236
    /**
237
     * Delete row from table
238
     *
239
     * @access public
240
     *
241
     * @param string $table Table name
242
     * @param string $conditions Conditions to search
243
     * @param array $params Params array
244
     *
245
     * @return bool
246
     */
247
    public function delete($table, $conditions, array $params = [])
248
    {
249
        return $this->conn->prepare("DELETE FROM {$table} WHERE {$conditions};")->execute($params);
250
    }
251
252
    /**
253
     * Count element in sub-query
254
     *
255
     * @access public
256
     *
257
     * @param string $query Query
258
     * @param string $table Table name
259
     *
260
     * @return integer|boolean
261
     */
262
    public function count($query = '', $table = '')
263
    {
264
        if ($query) {
265
            $sth = $this->conn->prepare("SELECT COUNT(*) FROM ({$query}) AS m;");
266
        } elseif ($table) {
267
            $sth = $this->conn->prepare("SELECT COUNT(*) FROM {$table} AS m;");
268
        } else {
269
            return false;
270
        }
271
        if ($sth->execute()) {
272
            return $sth->fetchColumn();
273
        }
274
275
        return false;
276
    }
277
278
    /**
279
     * Exists element in the table by params
280
     *
281
     * @access public
282
     *
283
     * @param string $table Table name
284
     * @param array $params Params array
285
     *
286
     * @return bool
287
     */
288
    public function exists($table, array $params = [])
289
    {
290
        $keys = [];
291
292
        foreach ($params AS $key => $val) {
293
            $keys[] = $table . '.' . $key . '=\'' . $val . '\'';
294
        }
295
296
        $sth = $this->conn->prepare('SELECT * FROM ' . $table . ' WHERE ' . implode(' AND ', $keys) . ' LIMIT 1;');
297
        /** @noinspection PdoApiUsageInspection */
298
        $sth->execute();
299
300
        return (bool)$sth->rowCount();
301
    }
302
}
303