Passed
Push — main ( 8cd2b3...6b394b )
by BRUNO
02:00
created

DatalayerTrait::setLogSQL()   B

Complexity

Conditions 10
Paths 2

Size

Total Lines 30
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 10
eloc 21
c 4
b 0
f 0
nc 2
nop 2
dl 0
loc 30
rs 7.6666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace BMorais\Database;
3
4
/**
5
 * CLASS TRAIT DATALAYER
6
 * This class of execution methods in the database
7
 *
8
 * @author Bruno Morais <[email protected]>
9
 * @copyright MIT, bmorais.com
10
 * @package bmorais\database
11
 * @subpackage class
12
 * @access private
13
 */
14
use PDO;
15
use PDOException;
16
use PDOStatement;
17
use stdClass;
18
19
trait DatalayerTrait
20
{
21
    /** @var PDO|null
22
     * @deprecated
23
     * */
24
    protected $instance = null;
25
26
    /** @var string
27
     *  @deprecated
28
     */
29
    protected string $fields;
30
31
    /** @var PDOStatement|null
32
     *   @deprecated */
33
    protected $prepare = null;
34
35
    /** @var string
36
     *  @deprecated
37
     */
38
    protected $database = CONFIG_DATA_LAYER["dbname"];
39
40
    /** @var string
41
     *  @deprecated
42
     */
43
    protected $classModel;
44
45
    /** @var string
46
     * @deprecated
47
     */
48
    protected $tableName;
49
50
    /** @var string */
51
    private $tableAlias;
52
53
    /** @var array
54
     * @deprecated
55
     */
56
    protected $resultArray = array();
57
58
    /** @var string */
59
    private $logSQL;
60
61
    /** @var PDOException */
62
    private $error;
63
64
    /** @var string */
65
    private string $query = "";
66
67
    /** @var array */
68
    private array $params = [];
69
70
71
    /** @return PDO|false */
72
    private function getInstance()
73
    {
74
        try {
75
            if (strpos($_SERVER['SERVER_NAME'], mb_strtolower(CONFIG_DATA_LAYER["homologation"])) && !strpos($this->getDatabase(), ucfirst(CONFIG_DATA_LAYER["homologation"]))) {
76
                $database = $this->getDatabase().ucfirst(CONFIG_DATA_LAYER["homologation"] ?? "");
77
                $this->setDatabase($database);
78
            }
79
80
            if (empty($this->getInstance())) {
81
                $instance = new PDO(
82
                    CONFIG_DATA_LAYER['driver'] . ':host=' . CONFIG_DATA_LAYER['host'] . ';dbname=' . $this->getDatabase() . ';port=' . CONFIG_DATA_LAYER['port'],
83
                    CONFIG_DATA_LAYER['username'],
84
                    CONFIG_DATA_LAYER['passwd'],
85
                    CONFIG_DATA_LAYER['options']
86
                );
87
                $this->setInstance($instance);
88
            }
89
90
            return $this->getInstance();
91
        } catch (PDOException $e) {
92
            $this->setError($e);
93
        }
94
95
    }
96
97
    /**
98
     * @param ?PDO $pdo
99
     * @return Crud
100
     *
101
     */
102
    protected function setInstance(?PDO $pdo): self
103
    {
104
        $this->instance = $pdo;
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$instance has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

104
        /** @scrutinizer ignore-deprecated */ $this->instance = $pdo;
Loading history...
105
        return $this;
106
    }
107
108
    /**
109
     * @param string $database
110
     * @return $this
111
     */
112
    protected function setDatabase(string $database): self
113
    {
114
        $this->database = $database;
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$database has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

114
        /** @scrutinizer ignore-deprecated */ $this->database = $database;
Loading history...
115
        $this->setInstance(null);
116
        return $this;
117
    }
118
119
    /**
120
     * @return string
121
     */
122
    protected function getDatabase(): string
123
    {
124
        return $this->database ?? "";
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$database has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

124
        return /** @scrutinizer ignore-deprecated */ $this->database ?? "";
Loading history...
125
    }
126
127
    /**
128
     * @param string $fields
129
     * @return Crud
130
     */
131
    protected function setFields(string $fields): self
132
    {
133
        $this->fields = $fields;
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$fields has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

133
        /** @scrutinizer ignore-deprecated */ $this->fields = $fields;
Loading history...
134
        return $this;
135
    }
136
137
    /**
138
     * @return string
139
     */
140
    protected function getFields():string
141
    {
142
        return $this->fields;
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$fields has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

142
        return /** @scrutinizer ignore-deprecated */ $this->fields;
Loading history...
143
    }
144
145
    /**
146
        * @param string $tableName
147
        * @param string $tableAlias
148
        * @return CrudBuilder|Crud|DatalayerTrait
149
     */
150
    protected function setTable(string $tableName, string $tableAlias = ""): self
151
    {
152
        if (!empty($tableAlias))
153
            $this->tableAlias = $tableAlias;
154
        $this->tableName = $tableName;
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$tableName has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

154
        /** @scrutinizer ignore-deprecated */ $this->tableName = $tableName;
Loading history...
155
        return $this;
156
    }
157
158
    /**
159
     * @return string
160
     */
161
    protected function getTable(): string
162
    {
163
        return $this->tableName ?? "";
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$tableName has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

163
        return /** @scrutinizer ignore-deprecated */ $this->tableName ?? "";
Loading history...
164
    }
165
166
    protected function getTableAlias(): string
167
    {
168
        return $this->tableAlias ?? "";
169
    }
170
171
    /**
172
     * @param string $classModel
173
     * @return Crud
174
     */
175
    protected function setClassModel(string $classModel): self
176
    {
177
        $this->classModel = $classModel;
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$classModel has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

177
        /** @scrutinizer ignore-deprecated */ $this->classModel = $classModel;
Loading history...
178
        return $this;
179
    }
180
181
    protected function getClassModel(): string
182
    {
183
        return $this->classModel;
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$classModel has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

183
        return /** @scrutinizer ignore-deprecated */ $this->classModel;
Loading history...
184
    }
185
186
    /**
187
     * @param string $classModel
188
     * @return Crud
189
     */
190
    protected function setPrepare(PDOStatement $prepare): self
191
    {
192
        $this->prepare = $prepare;
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$prepare has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

192
        /** @scrutinizer ignore-deprecated */ $this->prepare = $prepare;
Loading history...
193
        return $this;
194
    }
195
196
    protected function getPrepare(): PDOStatement
197
    {
198
        return $this->prepare;
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$prepare has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

198
        return /** @scrutinizer ignore-deprecated */ $this->prepare;
Loading history...
Bug Best Practice introduced by
The expression return $this->prepare could return the type null which is incompatible with the type-hinted return PDOStatement. Consider adding an additional type-check to rule them out.
Loading history...
199
    }
200
201
    /**
202
        * @param string $query
203
        * @param array|null $params
204
        * @return PDOStatement|void
205
     */
206
    protected function executeSQL(string $query, ?array $params = null)
207
    {
208
        try {
209
            $this->setPrepare($this->getInstance()->prepare($query));
210
            $this->setLogSQL($query, $params);
211
            $this->getPrepare()->execute($params);
212
            return $this->getPrepare();
213
        } catch (PDOException $e) {
214
            $this->setError($e);
215
        }
216
    }
217
218
    /**
219
     * @param $prepare
220
     * @return int|false
221
     */
222
    protected function count(PDOStatement $prepare = null): ?int
223
    {
224
        try {
225
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
226
            return $prepare->rowCount();
227
        } catch (PDOException $e) {
228
            $this->setError($e);}
229
    }
230
231
    /**
232
     * @param $prepare
233
     * @return array|false
234
     */
235
    protected function fetchArrayAssoc(PDOStatement $prepare = null): ?array
236
    {
237
        try {
238
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
239
            $dados = $prepare->fetchAll(PDO::FETCH_ASSOC);
240
            $this->resultArray = $dados;
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$resultArray has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

240
            /** @scrutinizer ignore-deprecated */ $this->resultArray = $dados;
Loading history...
241
            return $dados;
242
        } catch (PDOException $e) {
243
            $this->setError($e);
244
        }
245
    }
246
247
    /**
248
     * @param $prepare
249
     * @return array|false
250
     */
251
    protected function fetchArrayObj(PDOStatement $prepare = null): ?array
252
    {
253
        try {
254
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
255
            $dados = $prepare->fetchAll(PDO::FETCH_OBJ);
256
            $this->resultArray = $dados;
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$resultArray has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

256
            /** @scrutinizer ignore-deprecated */ $this->resultArray = $dados;
Loading history...
257
            return $dados;
258
        } catch (PDOException $e) {
259
            $this->setError($e);
260
        }
261
    }
262
263
    /**
264
     * @param $prepare
265
     * @param String|null $class
266
     * @return array|false
267
     */
268
    protected function fetchArrayClass(PDOStatement $prepare = null, string $class = null): ?array
269
    {
270
        try {
271
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
272
            $class = empty($class) ? $this->classModel : $class;
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$classModel has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

272
            $class = empty($class) ? /** @scrutinizer ignore-deprecated */ $this->classModel : $class;
Loading history...
273
            $dados = $prepare->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, CONFIG_DATA_LAYER["directory_models"] . $class);
274
            $this->resultArray = $dados;
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$resultArray has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

274
            /** @scrutinizer ignore-deprecated */ $this->resultArray = $dados;
Loading history...
275
            return $dados;
276
        } catch (PDOException $e) {
277
            $this->setError($e);
278
        }
279
    }
280
281
    /**
282
     * @param $prepare
283
     * @return array|false
284
     */
285
    protected function fetchOneAssoc(PDOStatement $prepare = null): ?array
286
    {
287
        try {
288
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
289
            $dados = $prepare->fetch(PDO::FETCH_ASSOC);
290
            return $dados;
291
        } catch (PDOException $e) {
292
            $this->setError($e);
293
        }
294
    }
295
296
    /**
297
     * @param $prepare
298
     * @return stdClass|false
299
     */
300
    protected function fetchOneObj(PDOStatement $prepare = null): ?stdClass
301
    {
302
        try {
303
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
304
            $dados = $prepare->fetch(PDO::FETCH_OBJ);
305
            return $dados;
306
        } catch (PDOException $e) {
307
            $this->setError($e);
308
        }
309
    }
310
311
    /**
312
     * @param $prepare
313
     * @param String|null $class
314
     * @return array|false
315
     */
316
    protected function fetchOneClass(PDOStatement $prepare = null, string $class = null): ?object
317
    {
318
        try {
319
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
320
            $class = empty($class) ? $this->classModel : $class;
0 ignored issues
show
Deprecated Code introduced by
The property BMorais\Database\DatalayerTrait::$classModel has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

320
            $class = empty($class) ? /** @scrutinizer ignore-deprecated */ $this->classModel : $class;
Loading history...
321
            return $prepare->fetchObject(CONFIG_DATA_LAYER["directory_models"] . $class);
322
        } catch (PDOException $e) {
323
            $this->setError($e);
324
        }
325
    }
326
327
    /**
328
     * @return bool
329
     */
330
    protected function beginTrasaction(): ?bool
331
    {
332
        try {
333
            $this->getInstance()->beginTransaction();
334
            return true;
335
        } catch (PDOException $e) {
336
            $this->setError($e);
337
        }
338
339
    }
340
341
    /**
342
     * @return bool|null
343
     */
344
    protected function commitTransaction(): ?bool
345
    {
346
        try {
347
            $this->getInstance()->commit();
348
            return true;
349
        } catch (PDOException $e) {
350
            $this->setError($e);
351
        }
352
    }
353
354
    /**
355
     * @return bool|null
356
     *
357
     */
358
    protected function rollBackTransaction(): ?bool
359
    {
360
361
        try {
362
            $this->getInstance()->rollBack();
363
            return true;
364
        } catch (PDOException $e) {
365
            $this->setError($e);
366
        }
367
    }
368
369
    /**
370
     *  @return string|null
371
     *  */
372
    private function lastId(): ?string
373
    {
374
        try {
375
            return $this->getInstance()->lastInsertId();
376
        } catch (PDOException $e) {
377
            $this->setError($e);
378
        }
379
    }
380
381
    /**
382
     * @param $sql_string
383
     * @param array|null $params
384
     * @return void
385
     */
386
    private function setLogSQL($sql_string, ?array $params = null)
387
    {
388
        if (!empty($params)) {
389
            $indexed = $params == array_values($params);
390
            foreach ($params as $k => $v) {
391
                if (is_object($v)) {
392
                    if ($v instanceof \DateTime) {
393
                        $v = $v->format('Y-m-d H:i:s');
394
                    } else {
395
                        continue;
396
                    }
397
                } elseif (is_string($v)) {
398
                    $v = "'$v'";
399
                } elseif ($v === null) {
400
                    $v = 'NULL';
401
                } elseif (is_array($v)) {
402
                    $v = implode(',', $v);
403
                }
404
405
                if ($indexed) {
406
                    $sql_string = preg_replace('/\?/', $v, $sql_string, 1);
407
                } else {
408
                    if ($k[0] != ':') {
409
                        $k = ':' . $k;
410
                    } //add leading colon if it was left out
411
                    $sql_string = str_replace($k, $v, $sql_string);
412
                }
413
            }
414
        }
415
        $this->logSQL = $sql_string;
416
    }
417
418
    /**
419
     * @param PDOException $e
420
     * @return void
421
     */
422
    private function setError(PDOException $e)
423
    {
424
        $this->error = $e;
425
        throw new PDOException("{$e->getMessage()}<br/><b>SQL:</b> {$this->getSQL()}");
0 ignored issues
show
Bug introduced by
It seems like getSQL() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

425
        throw new PDOException("{$e->getMessage()}<br/><b>SQL:</b> {$this->/** @scrutinizer ignore-call */ getSQL()}");
Loading history...
426
427
    }
428
}
429