Completed
Push — master ( 81cd21...259983 )
by Agel_Nash
02:37
created

IlluminateDriver::getInsertId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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() : Connection
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() : Connection
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() : DriverInterface
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() : bool
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() : int
145
    {
146 8
        return $this->affected_rows;
147
    }
148
149
    /**
150
     * @return string
151
     * @throws Exceptions\Exception
152
     */
153 1
    public function getVersion() : string
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) : int
164
    {
165 9
        return $result->rowCount();
166
    }
167
168
    /**
169
     * {@inheritDoc}
170
     */
171 19
    public function setCharset(string $charset, string $collation, $method = null) : bool
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) : bool
185
    {
186 19
        return $result instanceof PDOStatement;
187
    }
188
189
    /**
190
     * @param PDOStatement $result
191
     * @return int
192
     */
193 1
    public function numFields($result) : int
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) :? string
204
    {
205 1
        $field = $result->getColumnMeta($col);
206 1
        return $field['name'] ?? null;
207
    }
208
209
    /**
210
     * @param string $name
211
     * @return bool
212
     * @throws Exceptions\Exception
213
     */
214
    public function selectDb(string $name) : bool
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(string $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
            $this->lastErrorNo = $this->isResult($result) ? ($result->errorCode() ?? $exception->getCode()) : '';
277 2
            throw (new Exceptions\QueryException($exception->getMessage(), $exception->getCode()))
278 2
                ->setQuery($query);
279
        }
280
281 19
        return $result;
282
    }
283
284
    /**
285
     * @param string $name
286
     * @param $result
287
     * @return array
288
     * @throws Exceptions\Exception
289
     */
290 3
    public function getColumn(string $name, $result) : array
291
    {
292 3
        $col = [];
293
294 3
        if ($result instanceof PDOStatement) {
295 3
            while ($row = $this->getRow($result)) {
296 3
                $col[] = $row[$name];
297
            }
298
        }
299
300 3
        return $col;
301
    }
302
303
    /**
304
     * @param $result
305
     * @return array
306
     */
307 1
    public function getColumnNames($result) : array
308
    {
309 1
        $names = [];
310
311 1
        if ($result instanceof PDOStatement) {
312 1
            $limit = $this->numFields($result);
313 1
            for ($i = 0; $i < $limit; $i++) {
314 1
                $names[] = $this->fieldName($result, $i);
315
            }
316
        }
317
318 1
        return $names;
319
    }
320
321
    /**
322
     * @param $result
323
     * @return bool|mixed
324
     * @throws Exceptions\Exception
325
     */
326 3
    public function getValue($result)
327
    {
328 3
        $out = false;
329
330 3
        if ($result instanceof PDOStatement) {
331 3
            $result = $this->getRow($result, 'num');
332 3
            $out = $result[0] ?? false;
333
        }
334
335 3
        return $out;
336
    }
337
338
    /**
339
     * @param $result
340
     * @return array|mixed
341
     * @throws Exceptions\Exception
342
     */
343 1
    public function getTableMetaData($result)
344
    {
345 1
        $out = [];
346
347 1
        if ($result instanceof PDOStatement) {
348 1
            while ($row = $this->getRow($result)) {
349 1
                $fieldName = $row['Field'];
350 1
                $out[$fieldName] = $row;
351
            }
352
        }
353
354 1
        return $out;
355
    }
356
357
    /**
358
     * @return string|null
359
     * @throws Exceptions\Exception
360
     */
361 1
    public function getLastError() :? string
362
    {
363 1
        return (string)($this->getConnect()->getPdo()->errorInfo()[2] ?? $this->lastError[2]);
364
    }
365
366
    /**
367
     * @return string|null
368
     * @throws Exceptions\Exception
369
     */
370 1
    public function getLastErrorNo() :? string
371
    {
372 1
        return (string)($this->getConnect()->getPdo()->errorInfo()[1] ?? $this->lastErrorNo);
373
    }
374
375
    /**
376
     * {@inheritDoc}
377
     * @param \PDOStatement $result
378
     */
379
    public function dataSeek(&$result, $position) : bool
380
    {
381
        throw new Exceptions\DriverException('No implemented');
382
    }
383
}
384