Passed
Push — master ( 63aba0...c4286f )
by Oleg
04:57
created

DbConnection::rawQuery()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
c 0
b 0
f 0
rs 9.4285
nc 4
cc 3
eloc 10
nop 4
1
<?php /** MicroDataBaseConnection */
2
3
namespace Micro\Db;
4
5
use Micro\Base\Exception;
6
7
/**
8
 * Connection class file.
9
 *
10
 * @author Oleg Lunegov <[email protected]>
11
 * @link https://github.com/linpax/microphp-framework
12
 * @copyright Copyright &copy; 2013 Oleg Lunegov
13
 * @license /LICENSE
14
 * @package Micro
15
 * @subpackage Db
16
 * @version 1.0
17
 * @since 1.0
18
 */
19
class DbConnection extends Connection
20
{
21
    /** @var \PDO|null $conn Connection to DB */
22
    protected $conn;
23
24
25
    /**
26
     * Construct for this class
27
     *
28
     * @access public
29
     *
30
     * @param array $config
31
     * @param array $options
32
     *
33
     * @result void
34
     * @throws Exception
35
     */
36
    public function __construct(array $config = [], array $options = [])
37
    {
38
        parent::__construct();
39
40
        try {
41
            $this->conn = new \PDO($config['connectionString'], $config['username'], $config['password'],
42
                    $options
43
                );
44
        } catch (\PDOException $e) {
45
            if (!array_key_exists('ignoreFail', $config) || !$config['ignoreFail']) {
46
                throw new Exception('Connect to DB failed: '.$e->getMessage());
47
            }
48
        }
49
    }
50
51
    /**
52
     * Destructor for this class
53
     *
54
     * @access public
55
     * @return void
56
     */
57
    public function __destruct()
58
    {
59
        $this->conn = null;
60
    }
61
62
    /**
63
     * @inheritdoc
64
     */
65
    public function rawQuery($query = '', array $params = [], $fetchType = \PDO::FETCH_ASSOC, $fetchClass = 'Model')
66
    {
67
        $sth = $this->conn->prepare($query);
68
69
        if ($fetchType === \PDO::FETCH_CLASS) {
70
            /** @noinspection PhpMethodParametersCountMismatchInspection */
71
            $sth->setFetchMode($fetchType, ucfirst($fetchClass), ['new' => false]);
72
        } else {
73
            $sth->setFetchMode($fetchType);
74
        }
75
76
        foreach ($params AS $name => $value) {
77
            $sth->bindValue($name, $value);
78
        }
79
80
        $sth->execute();
81
82
        return $sth->fetchAll();
83
    }
84
85
    /**
86
     * @inheritdoc
87
     */
88
    public function listDatabases()
89
    {
90
        $sth = $this->conn->query('SHOW DATABASES;');
91
92
        $result = [];
93
        foreach ($sth->fetchAll() AS $row) {
94
            $result[] = $row[0];
95
        }
96
97
        return $result;
98
    }
99
100
    /**
101
     * @inheritdoc
102
     */
103
    public function infoDatabase($dbName)
104
    {
105
        $sth = $this->conn->query("SHOW TABLE STATUS FROM {$dbName};");
106
107
        $result = [];
108
        foreach ($sth->fetchAll() AS $row) {
109
            $result[] = [
110
                'name' => $row['Name'],
111
                'engine' => $row['Engine'],
112
                'rows' => $row['Rows'],
113
                'length' => $row['Avg_row_length'],
114
                'increment' => $row['Auto_increment'],
115
                'collation' => $row['Collation']
116
            ];
117
        }
118
119
        return $result;
120
    }
121
122
    /**
123
     * @inheritdoc
124
     */
125
    public function tableExists($table)
126
    {
127
        return in_array($table, $this->listTables(), false);
128
    }
129
130
    /**
131
     * @inheritdoc
132
     */
133
    public function listTables()
134
    {
135
        return $this->conn->query('SHOW TABLES;')->fetchAll(\PDO::FETCH_COLUMN, 0);
136
    }
137
138
    /**
139
     * @inheritdoc
140
     */
141
    public function createTable($name, array $elements = [], $params = '')
142
    {
143
        return $this->conn->exec(
144
            sprintf('SELECT TABLE IF NOT EXISTS `%s` (%s) %s;', $name, implode(',', $elements), $params)
145
        );
146
    }
147
148
    /**
149
     * @inheritdoc
150
     */
151
    public function clearTable($name)
152
    {
153
        return $this->conn->exec("TRUNCATE {$name};");
154
    }
155
156
    /**
157
     * @inheritdoc
158
     */
159
    public function removeTable($name)
160
    {
161
        return $this->conn->exec("DROP TABLE {$name};");
162
    }
163
164
    /**
165
     * @inheritdoc
166
     */
167
    public function fieldExists($field, $table)
168
    {
169
        foreach ($this->listFields($table) AS $tbl) {
170
            if ($tbl['field'] === $field) {
171
                return true;
172
            }
173
        }
174
175
        return false;
176
    }
177
178
    /**
179
     * @inheritdoc
180
     */
181
    public function listFields($table)
182
    {
183
        $sth = $this->conn->query("SHOW COLUMNS FROM {$table};");
184
185
        $result = [];
186
        foreach ($sth->fetchAll(\PDO::FETCH_ASSOC) as $row) {
187
            $result[] = [
188
                'field' => $row['Field'],
189
                'type' => $row['Type'],
190
                'null' => $row['Null'],
191
                'key' => $row['Key'],
192
                'default' => $row['Default'],
193
                'extra' => $row['Extra']
194
            ];
195
        }
196
197
        return $result;
198
    }
199
200
    /**
201
     * @inheritdoc
202
     */
203
    public function fieldInfo($field, $table)
204
    {
205
        return $this->conn->query("SELECT {$field} FROM {$table} LIMIT 1;")->getColumnMeta(0);
206
    }
207
208
    /**
209
     * @inheritdoc
210
     */
211
    public function switchDatabase($dbName)
212
    {
213
        if ($this->conn->exec("USE {$dbName};") !== false) {
214
            return true;
215
        } else {
216
            return false;
217
        }
218
    }
219
220
    /**
221
     * @inheritdoc
222
     */
223
    public function insert($table, array $line = [], $multi = false)
224
    {
225
        $fields = '`'.implode('`, `', array_keys($multi ? $line[0] : $line)).'`';
226
        $values = ':'.implode(', :', array_keys($multi ? $line[0] : $line));
227
        $rows = $multi ? $line : [$line];
228
        $id = null;
229
230
        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...
231
            $this->conn->beginTransaction();
232
233
            $dbh = null;
234
            foreach ($rows AS $row) {
235
                $dbh = $this->conn->prepare("INSERT INTO {$table} ({$fields}) VALUES ({$values});")->execute($row);
236
            }
237
238
            $id = $dbh ? $this->conn->lastInsertId() : false;
239
            $this->conn->commit();
240
        }
241
242
        return $id ?: false;
243
    }
244
245
    /**
246
     * @inheritdoc
247
     */
248
    public function update($table, array $elements = [], $conditions = '')
249
    {
250
        $keys = array_keys($elements);
251
        if (0 === count($keys)) {
252
            return false;
253
        }
254
255
        $valStr = [];
256
        foreach ($keys as $key) {
257
            $valStr[] = '`'.$key.'` = :'.$key;
258
        }
259
        $valStr = implode(',', $valStr);
260
261
        if ($conditions) {
262
            $conditions = 'WHERE '.$conditions;
263
        }
264
265
        return $this->conn->prepare("UPDATE {$table} SET {$valStr} {$conditions};")->execute($elements);
266
    }
267
268
    /**
269
     * @inheritdoc
270
     */
271
    public function delete($table, $conditions, array $ph = [])
272
    {
273
        return $this->conn->prepare("DELETE FROM {$table} WHERE {$conditions};")->execute($ph);
274
    }
275
276
    /**
277
     * @inheritdoc
278
     */
279
    public function exists($table, array $params = [])
280
    {
281
        $keys = [];
282
        foreach ($params AS $key => $val) {
283
            $keys[] = '`'.$table.'`.`'.$key.'`="'.$val.'"';
284
        }
285
286
        $sth = $this->conn->prepare('SELECT * FROM `'.$table.'` WHERE '.implode(' AND ', $keys).' LIMIT 1;');
287
        /** @noinspection PdoApiUsageInspection */
288
        $sth->execute();
289
290
        return (bool)$sth->rowCount();
291
    }
292
293
    /**
294
     * @inheritdoc
295
     */
296
    public function count($subQuery = '', $table = '')
297
    {
298
        if ($subQuery) {
299
            $sth = $this->conn->prepare("SELECT COUNT(*) FROM ({$subQuery}) AS m;");
300
        } elseif ($table) {
301
            $sth = $this->conn->prepare("SELECT COUNT(*) FROM {$table} AS m;");
302
        } else {
303
            return false;
304
        }
305
        if ($sth->execute()) {
306
            return $sth->fetchColumn();
307
        }
308
309
        return false;
310
    }
311
}
312