Test Failed
Push — master ( 807926...ca6dd2 )
by Agel_Nash
04:04
created

IlluminateDriver   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 378
Duplicated Lines 0 %

Test Coverage

Coverage 85.95%

Importance

Changes 0
Metric Value
dl 0
loc 378
ccs 104
cts 121
cp 0.8595
rs 6
c 0
b 0
f 0
wmc 55

24 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A isResult() 0 3 1
B getRow() 0 22 5
A getInsertId() 0 3 1
A getAffectedRows() 0 3 1
A getConnect() 0 7 2
A isConnected() 0 3 2
A disconnect() 0 9 2
A escape() 0 9 2
A connect() 0 20 2
A numFields() 0 3 1
A setCharset() 0 7 2
A getVersion() 0 3 1
A getRecordCount() 0 3 1
A selectDb() 0 5 1
A dataSeek() 0 3 1
A getColumnNames() 0 12 3
A fieldName() 0 4 2
A getValue() 0 10 3
A getColumn() 0 11 3
A getTableMetaData() 0 12 3
D query() 0 27 11
A getLastErrorNo() 0 5 2
A getLastError() 0 5 2

How to fix   Complexity   

Complex Class

Complex classes like IlluminateDriver often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use IlluminateDriver, and based on these observations, apply Extract Interface, too.

1
<?php namespace AgelxNash\Modx\Evo\Database\Drivers;
2
3
use AgelxNash\Modx\Evo\Database\Interfaces\DriverInterface;
4
use AgelxNash\Modx\Evo\Database\Exceptions;
5
use Illuminate\Database\Capsule\Manager as Capsule;
6
use Illuminate\Database\Connection;
7
use PDOStatement;
8
9
class IlluminateDriver implements DriverInterface
10
{
11
    /**
12
     * @var Connection
13
     */
14
    protected $conn;
15
16
    /**
17
     * @var Capsule
18
     */
19
    protected $capsule;
20
21
    private $affected_rows = 0;
22
23
    /**
24
     * @var array
25
     */
26
    protected $config;
27
28
    /**
29
     * @var array
30
     */
31
    public $lastError;
32
33
    /**
34
     * @var string
35
     */
36
    public $lastErrorNo;
37
38
    protected $driver = 'mysql';
39
40
    /**
41
     * {@inheritDoc}
42
     */
43 19
    public function __construct(array $config = [])
44
    {
45 19
        $this->capsule = new Capsule;
46
47 19
        $this->capsule->setAsGlobal();
48
49 19
        $this->capsule->bootEloquent();
50
51 19
        $this->config = $config;
52 19
    }
53
54
    /**
55
     * @return Connection
56
     * @throws Exceptions\Exception
57
     */
58 19
    public function getConnect()
59
    {
60 19
        if (! $this->isConnected()) {
61 1
            return $this->connect();
62
        }
63
64 19
        return $this->conn;
65
    }
66
67
    /**
68
     * @return
69
     * @throws Exceptions\Exception
70
     */
71 19
    public function connect()
72
    {
73
        try {
74 19
            $this->capsule->addConnection([
75 19
                'driver'    => $this->driver,
76 19
                'host'      => $this->config['host'],
77 19
                'database'  => $this->config['base'],
78 19
                'username'  => $this->config['user'],
79 19
                'password'  => $this->config['pass'],
80 19
                'charset'   => $this->config['charset'],
81 19
                'collation' => $this->config['collation'],
82 19
                'prefix'    => $this->config['prefix'],
83
            ]);
84
85 19
            $this->conn = $this->capsule->getConnection();
86
        } catch (\Exception $exception) {
87
            throw new Exceptions\ConnectException($exception->getMessage(), $exception->getCode());
88
        }
89
90 19
        return $this->conn;
91
    }
92
93
    /**
94
     * {@inheritDoc}
95
     */
96 1
    public function disconnect()
97
    {
98 1
        if ($this->isConnected()) {
99 1
            $this->conn->disconnect();
100
        }
101
102 1
        $this->conn = null;
103
104 1
        return $this;
105
    }
106
107
    /**
108
     * @return bool
109
     */
110 19
    public function isConnected()
111
    {
112 19
        return ($this->conn instanceof Connection && $this->conn->getDatabaseName());
113
    }
114
115
    /**
116
     * @param $data
117
     * @return mixed
118
     * @throws Exceptions\Exception
119
     */
120 1
    public function escape($data)
121
    {
122
        /**
123
         * It's not secure
124
         * But need for backward compatibility
125
         */
126
127 1
        $quote = $this->getConnect()->getPdo()->quote($data);
128 1
        return strpos($quote, '\'') === 0 ? mb_substr($quote, 1, -1) : $quote;
129
    }
130
131
    /**
132
     * @return mixed
133
     * @throws Exceptions\Exception
134
     */
135 3
    public function getInsertId()
136
    {
137 3
        return $this->getConnect()->getPdo()->lastInsertId();
138
    }
139
140
    /**
141
     * @return int
142
     * @throws Exceptions\Exception
143
     */
144 8
    public function getAffectedRows()
145
    {
146 8
        return $this->affected_rows;
147
    }
148
149
    /**
150
     * @return string
151
     * @throws Exceptions\Exception
152
     */
153 1
    public function getVersion()
154
    {
155 1
        return $this->getConnect()->getPdo()->getAttribute(\PDO::ATTR_SERVER_VERSION);
156
        //return $this->getConnect()->server_info;
157
    }
158
159
    /**
160
     * @param PDOStatement $result
161
     * @return int
162
     */
163 9
    public function getRecordCount($result)
164
    {
165 9
        return $result->rowCount();
166
    }
167
168
    /**
169
     * {@inheritDoc}
170
     */
171 19
    public function setCharset($charset, $collation, $method = null)
172
    {
173 19
        if ($method === null) {
174
            $method = $this->config['method'];
175
        }
176
177 19
        return (bool)$this->query($method . ' ' . $charset . ' COLLATE ' . $collation);
178
    }
179
180
    /**
181
     * @param $result
182
     * @return bool
183
     */
184 19
    public function isResult($result)
185
    {
186 19
        return $result instanceof PDOStatement;
187
    }
188
189
    /**
190
     * @param PDOStatement $result
191
     * @return int
192
     */
193 1
    public function numFields($result)
194
    {
195 1
        return $result->columnCount();
196
    }
197
198
    /**
199
     * @param PDOStatement $result
200
     * @param int $col
201
     * @return string|null
202
     */
203 1
    public function fieldName($result, $col = 0)
204
    {
205 1
        $field = $result->getColumnMeta($col);
206 1
        return isset($field['name']) ? $field['name'] : null;
207
    }
208
209
    /**
210
     * @param string $name
211
     * @return bool
212
     * @throws Exceptions\Exception
213
     */
214
    public function selectDb($name)
215
    {
216
        $this->getConnect()->setDatabaseName($name);
217
218
        return true;
219
    }
220
221
    /**
222
     * @param PDOStatement $result
223
     * @param string $mode
224
     * @return array|mixed|object|\stdClass
225
     * @throws Exceptions\Exception
226
     */
227 7
    public function getRow($result, $mode = 'assoc')
228
    {
229
        switch ($mode) {
230 7
            case 'assoc':
231 5
                $out = $result->fetch(\PDO::FETCH_ASSOC);
232 5
                break;
233 3
            case 'num':
234 3
                $out = $result->fetch(\PDO::FETCH_NUM);
235 3
                break;
236
            case 'object':
237
                $out = $result->fetchObject();
238
                break;
239
            case 'both':
240
                $out = $result->fetch(\PDO::FETCH_BOTH);
241
                break;
242
            default:
243
                throw new Exceptions\UnknownFetchTypeException(
244
                    "Unknown get type ($mode) specified for fetchRow - must be empty, 'assoc', 'num' or 'both'."
245
                );
246
        }
247
248 7
        return $out;
249
    }
250
251
    /**
252
     * @param string $query
253
     * @return mixed
254
     * @throws Exceptions\Exception
255
     */
256 19
    public function query($query)
257
    {
258 19
        $result = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
259
        try {
260 19
            $result = $this->getConnect()->getPdo()->prepare(
261 19
                $query,
262
                [
263 19
                    \PDO::ATTR_CURSOR => \PDO::CURSOR_SCROLL
264
                ]
265
            );
266 19
            $result->setFetchMode(\PDO::FETCH_ASSOC);
267 19
            if ($result->execute() === false) {
268
                $result = false;
269
            }
270 19
            $this->affected_rows = \is_bool($result) ? 0 : $result->rowCount();
271 19
            if ($this->affected_rows === 0 && $this->isResult($result) && 0 !== mb_stripos(trim($query), 'SELECT')) {
272 19
                $result = true;
273
            }
274 2
        } catch (\Exception $exception) {
275 2
            $this->lastError = $this->isResult($result) ? $result->errorInfo() : [];
276 2
            $code = $this->isResult($result) ? $result->errorCode() : '';
277 2
            $this->lastErrorNo = $this->isResult($result) ? (empty($code) ? $exception->getCode() : $code) : '';
278 2
            throw (new Exceptions\QueryException($exception->getMessage(), $exception->getCode()))
279
                ->setQuery($query);
280
        }
281 19
282
        return $result;
283
    }
284
285
    /**
286
     * @param string $name
287
     * @param $result
288
     * @return array
289
     * @throws Exceptions\Exception
290 3
     */
291
    public function getColumn($name, $result)
292 3
    {
293
        $col = [];
294 3
295 3
        if ($result instanceof PDOStatement) {
296 3
            while ($row = $this->getRow($result)) {
297
                $col[] = $row[$name];
298
            }
299
        }
300 3
301
        return $col;
302
    }
303
304
    /**
305
     * @param $result
306
     * @return array
307 1
     */
308
    public function getColumnNames($result)
309 1
    {
310
        $names = [];
311 1
312 1
        if ($result instanceof PDOStatement) {
313 1
            $limit = $this->numFields($result);
314 1
            for ($i = 0; $i < $limit; $i++) {
315
                $names[] = $this->fieldName($result, $i);
316
            }
317
        }
318 1
319
        return $names;
320
    }
321
322
    /**
323
     * @param $result
324
     * @return bool|mixed
325
     * @throws Exceptions\Exception
326 3
     */
327
    public function getValue($result)
328 3
    {
329
        $out = false;
330 3
331 3
        if ($result instanceof PDOStatement) {
332 3
            $result = $this->getRow($result, 'num');
333
            $out = isset($result[0]) ? $result[0] : false;
334
        }
335 3
336
        return $out;
337
    }
338
339
    /**
340
     * @param $result
341
     * @return array|mixed
342
     * @throws Exceptions\Exception
343 1
     */
344
    public function getTableMetaData($result)
345 1
    {
346
        $out = [];
347 1
348 1
        if ($result instanceof PDOStatement) {
349 1
            while ($row = $this->getRow($result)) {
350 1
                $fieldName = $row['Field'];
351
                $out[$fieldName] = $row;
352
            }
353
        }
354 1
355
        return $out;
356
    }
357
358
    /**
359
     * @return string|null
360
     * @throws Exceptions\Exception
361 1
     */
362
    public function getLastError()
363 1
    {
364
        $pdo = $this->getConnect()->getPdo();
365
        $error = $pdo->errorInfo();
366
        return (string)(isset($error[2]) ? $error[2] : $this->lastError[2]);
367
    }
368
369
    /**
370 1
     * @return string|null
371
     * @throws Exceptions\Exception
372 1
     */
373
    public function getLastErrorNo()
374
    {
375
        $pdo = $this->getConnect()->getPdo();
376
        $error = $pdo->errorInfo();
377
        return (string)(isset($error[1]) ? $error[1] : $this->lastErrorNo);
378
    }
379
380
    /**
381
     * {@inheritDoc}
382
     * @param \PDOStatement $result
383
     */
384
    public function dataSeek(&$result, $position)
385
    {
386
        throw new Exceptions\DriverException('No implemented');
387
    }
388
}
389