Completed
Push — master ( 7b363d...433e34 )
by Oleg
07:56
created

MysqlDriver::delete()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 3
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
     * Get array fields into table
112
     *
113
     * @access public
114
     *
115
     * @param string $table Table name
116
     *
117
     * @return array
118
     */
119
    public function listFields($table)
120
    {
121
        $sth = $this->conn->query("SHOW COLUMNS FROM {$table};");
122
123
        $result = [];
124
        foreach ($sth->fetchAll(\PDO::FETCH_ASSOC) as $row) {
125
            $result[] = [
126
                'field' => $row['Field'],
127
                'type' => $row['Type'],
128
                'null' => $row['Null'],
129
                'key' => $row['Key'],
130
                'default' => $row['Default'],
131
                'extra' => $row['Extra']
132
            ];
133
        }
134
135
        return $result;
136
    }
137
138
    /**
139
     * Insert row into table
140
     *
141
     * @access public
142
     *
143
     * @param string $table Table name
144
     * @param array $line Line or lines to added
145
     * @param bool $multi Is multi rows
146
     *
147
     * @return bool
148
     */
149
    public function insert($table, array $line = [], $multi = false)
150
    {
151
        $fields = '`' . implode('`, `', array_keys($multi ? $line[0] : $line)) . '`';
152
153
        $values = ':'.implode(', :', array_keys($multi ? $line[0] : $line));
154
        $rows = $multi ? $line : [$line];
155
        $id = null;
156
157
        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...
158
            $this->conn->beginTransaction();
159
160
            $dbh = null;
161
            foreach ($rows AS $row) {
162
                $dbh = $this->conn->prepare("INSERT INTO {$table} ({$fields}) VALUES ({$values});")->execute($row);
163
            }
164
165
            $id = $dbh ? $this->conn->lastInsertId() : false;
166
            $this->conn->commit();
167
        }
168
169
        return $id ?: false;
170
    }
171
172
    /**
173
     * Update row in table
174
     *
175
     * @access public
176
     *
177
     * @param string $table Table name
178
     * @param array $elements Elements to update
179
     * @param string $conditions Conditions for search
180
     *
181
     * @return bool
182
     */
183 View Code Duplication
    public function update($table, array $elements = [], $conditions = '')
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...
184
    {
185
        $keys = array_keys($elements);
186
187
        if (0 === count($keys)) {
188
            return false;
189
        }
190
191
        $valStr = [];
192
193
        foreach ($keys as $key) {
194
            $valStr[] = '`'.$key.'` = :'.$key;
195
        }
196
197
        $valStr = implode(',', $valStr);
198
199
        if ($conditions) {
200
            $conditions = 'WHERE '.$conditions;
201
        }
202
203
        return $this->conn->prepare("UPDATE {$table} SET {$valStr} {$conditions};")->execute($elements);
204
    }
205
206
    /**
207
     * Exists element in the table by params
208
     *
209
     * @access public
210
     *
211
     * @param string $table Table name
212
     * @param array $params Params array
213
     *
214
     * @return bool
215
     */
216 View Code Duplication
    public function exists($table, array $params = [])
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...
217
    {
218
        $keys = [];
219
220
        foreach ($params AS $key => $val) {
221
            $keys[] = '`' . $key . '`="' . $val . '""';
222
        }
223
224
        $sth = $this->conn->prepare('SELECT * FROM ' . $table . ' WHERE ' . implode(' AND ', $keys) . ' LIMIT 1;');
225
        /** @noinspection PdoApiUsageInspection */
226
        $sth->execute();
227
228
        return (bool)$sth->rowCount();
229
    }
230
}
231