Passed
Push — main ( 672c9e...b97579 )
by BRUNO
02:28
created

DatalayerTrait::getClassModel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
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
     */
55
    private array $resultArray = [];
56
57
    /** @var string */
58
    private $logSQL;
59
60
    /** @var PDOException */
61
    private $error;
62
63
    /** @var string */
64
    private string $query = "";
65
66
    /** @var array */
67
    private array $params = [];
68
69
70
    /** @return PDO|false */
71
    private function getConnect()
72
    {
73
        try {
74
            if (strpos($_SERVER['SERVER_NAME'], mb_strtolower(CONFIG_DATA_LAYER["homologation"])) && !strpos($this->getDatabase(), ucfirst(CONFIG_DATA_LAYER["homologation"]))) {
75
                $database = $this->getDatabase().ucfirst(CONFIG_DATA_LAYER["homologation"] ?? "");
76
                $this->setDatabase($database);
77
            }
78
79
            if (empty($this->instance)) {
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

79
            if (empty(/** @scrutinizer ignore-deprecated */ $this->instance)) {
Loading history...
80
                $this->instance = new 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

80
                /** @scrutinizer ignore-deprecated */ $this->instance = new PDO(
Loading history...
81
                    CONFIG_DATA_LAYER['driver'] . ':host=' . CONFIG_DATA_LAYER['host'] . ';dbname=' . $this->getDatabase() . ';port=' . CONFIG_DATA_LAYER['port'],
82
                    CONFIG_DATA_LAYER['username'],
83
                    CONFIG_DATA_LAYER['passwd'],
84
                    CONFIG_DATA_LAYER['options']
85
                );
86
            }
87
88
            return $this->instance;
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

88
            return /** @scrutinizer ignore-deprecated */ $this->instance;
Loading history...
89
        } catch (PDOException $e) {
90
            $this->setError($e);
91
        }
92
93
    }
94
95
    /**
96
     * @param ?PDO $pdo
97
     * @return Crud
98
     *
99
     */
100
    protected function setInstance(?PDO $pdo): self
101
    {
102
        $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

102
        /** @scrutinizer ignore-deprecated */ $this->instance = $pdo;
Loading history...
103
        return $this;
104
    }
105
106
    protected function getInstance(): PDO
107
    {
108
        return $this->instance ?? $this->getConnect();
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

108
        return /** @scrutinizer ignore-deprecated */ $this->instance ?? $this->getConnect();
Loading history...
Bug Best Practice introduced by
The expression return $this->instance ?? $this->getConnect() could return the type false which is incompatible with the type-hinted return PDO. Consider adding an additional type-check to rule them out.
Loading history...
109
    }
110
111
    /**
112
     * @param string $database
113
     * @return $this
114
     */
115
    protected function setDatabase(string $database): self
116
    {
117
        if (strpos($_SERVER['SERVER_NAME'], mb_strtolower(CONFIG_DATA_LAYER["homologation"])) && !strpos($this->getDatabase(), ucfirst(CONFIG_DATA_LAYER["homologation"]))) {
118
            $database = $database.ucfirst(CONFIG_DATA_LAYER["homologation"] ?? "");
119
        }
120
121
        $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

121
        /** @scrutinizer ignore-deprecated */ $this->database = $database;
Loading history...
122
        $this->setInstance(null)->getInstance();
123
        return $this;
124
    }
125
126
    /**
127
     * @return string
128
     */
129
    protected function getDatabase(): string
130
    {
131
        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

131
        return /** @scrutinizer ignore-deprecated */ $this->database ?? "";
Loading history...
132
    }
133
134
    /**
135
     * @param string $fields
136
     * @return Crud
137
     */
138
    protected function setFields(string $fields): self
139
    {
140
        $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

140
        /** @scrutinizer ignore-deprecated */ $this->fields = $fields;
Loading history...
141
        return $this;
142
    }
143
144
    /**
145
     * @return string
146
     */
147
    protected function getFields():string
148
    {
149
        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

149
        return /** @scrutinizer ignore-deprecated */ $this->fields;
Loading history...
150
    }
151
152
    /**
153
        * @param string $tableName
154
        * @param string $tableAlias
155
        * @return CrudBuilder|Crud|DatalayerTrait
156
     */
157
    protected function setTable(string $tableName, string $tableAlias = ""): self
158
    {
159
        if (!empty($tableAlias))
160
            $this->tableAlias = $tableAlias;
161
        $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

161
        /** @scrutinizer ignore-deprecated */ $this->tableName = $tableName;
Loading history...
162
        return $this;
163
    }
164
165
    /**
166
     * @return string
167
     */
168
    protected function getTable(): string
169
    {
170
        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

170
        return /** @scrutinizer ignore-deprecated */ $this->tableName ?? "";
Loading history...
171
    }
172
173
    protected function getTableAlias(): string
174
    {
175
        return $this->tableAlias ?? "";
176
    }
177
178
    /**
179
     * @param string $classModel
180
     * @return Crud
181
     */
182
    protected function setClassModel(string $classModel): self
183
    {
184
        $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

184
        /** @scrutinizer ignore-deprecated */ $this->classModel = $classModel;
Loading history...
185
        return $this;
186
    }
187
188
    protected function getClassModel(): string
189
    {
190
        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

190
        return /** @scrutinizer ignore-deprecated */ $this->classModel;
Loading history...
191
    }
192
193
    /**
194
     * @param string $classModel
195
     * @return Crud
196
     */
197
    protected function setPrepare(PDOStatement $prepare): self
198
    {
199
        $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

199
        /** @scrutinizer ignore-deprecated */ $this->prepare = $prepare;
Loading history...
200
        return $this;
201
    }
202
203
    protected function getPrepare(): PDOStatement
204
    {
205
        return $this->prepare;
0 ignored issues
show
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...
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

205
        return /** @scrutinizer ignore-deprecated */ $this->prepare;
Loading history...
206
    }
207
208
    protected function getResult(): array
209
    {
210
       return $this->resultArray;
211
    }
212
213
    protected function setResult(array $array): self
214
    {
215
        $this->resultArray = $array;
216
        return $this;
217
    }
218
219
    /**
220
        * @param string $query
221
        * @param array|null $params
222
        * @return PDOStatement|void
223
     */
224
    protected function executeSQL(string $query, ?array $params = null)
225
    {
226
        try {
227
            $this->setPrepare($this->getInstance()->prepare($query));
228
            $this->setLogSQL($query, $params);
229
            $this->getPrepare()->execute($params);
230
            return $this->getPrepare();
231
        } catch (PDOException $e) {
232
            $this->setError($e);
233
        }
234
    }
235
236
    /**
237
     * @param $prepare
238
     * @return int|false
239
     */
240
    protected function count(PDOStatement $prepare = null): ?int
241
    {
242
        try {
243
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
244
            return $prepare->rowCount();
245
        } catch (PDOException $e) {
246
            $this->setError($e);}
247
    }
248
249
    /**
250
    * @param PDOStatement|null $prepare
251
    * @return array|null
252
     */
253
    protected function fetchArrayAssoc(PDOStatement $prepare = null): ?array
254
    {
255
        try {
256
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
257
            $dados = $prepare->fetchAll(PDO::FETCH_ASSOC);
258
            $this->setResult($dados);
259
            return $dados;
260
        } catch (PDOException $e) {
261
            $this->setError($e);
262
        }
263
    }
264
265
    /**
266
     * @param $prepare
267
     * @return array|false
268
     */
269
    protected function fetchArrayObj(PDOStatement $prepare = null): ?array
270
    {
271
        try {
272
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
273
            $dados = $prepare->fetchAll(PDO::FETCH_OBJ);
274
            $this->setResult($dados);
275
            return $dados;
276
        } catch (PDOException $e) {
277
            $this->setError($e);
278
        }
279
    }
280
281
    /**
282
     * @param $prepare
283
     * @param String|null $classModel
284
     * @return array|false
285
     */
286
    protected function fetchArrayClass(PDOStatement $prepare = null, string $classModel = null): ?array
287
    {
288
        try {
289
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
290
            $classModel = empty($classModel) ? $this->getClassModel() : $classModel;
291
            $dados = $prepare->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, CONFIG_DATA_LAYER["directory_models"] . $classModel);
292
            $this->setResult($dados);
293
            return $dados;
294
        } catch (PDOException $e) {
295
            $this->setError($e);
296
        }
297
    }
298
299
    /**
300
     * @param $prepare
301
     * @return array|false
302
     */
303
    protected function fetchOneAssoc(PDOStatement $prepare = null): ?array
304
    {
305
        try {
306
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
307
            return $prepare->fetch(PDO::FETCH_ASSOC);
308
        } catch (PDOException $e) {
309
            $this->setError($e);
310
        }
311
    }
312
313
    /**
314
    * @param PDOStatement|null $prepare
315
    * @return stdClass|null
316
     */
317
    protected function fetchOneObj(PDOStatement $prepare = null): ?stdClass
318
    {
319
        try {
320
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
321
            return $prepare->fetch(PDO::FETCH_OBJ);
322
        } catch (PDOException $e) {
323
            $this->setError($e);
324
        }
325
    }
326
327
    /**
328
     * @param $prepare
329
     * @param String|null $class
330
     * @return array|false
331
     */
332
    protected function fetchOneClass(PDOStatement $prepare = null, string $class = null): ?object
333
    {
334
        try {
335
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
336
            $class = empty($class) ? $this->getClassModel() : $class;
337
            return $prepare->fetchObject(CONFIG_DATA_LAYER["directory_models"] . $class);
338
        } catch (PDOException $e) {
339
            $this->setError($e);
340
        }
341
    }
342
343
    /**
344
     * @return bool
345
     */
346
    protected function beginTrasaction(): ?bool
347
    {
348
        try {
349
            $this->getInstance()->beginTransaction();
350
            return true;
351
        } catch (PDOException $e) {
352
            $this->setError($e);
353
        }
354
355
    }
356
357
    /**
358
     * @return bool|null
359
     */
360
    protected function commitTransaction(): ?bool
361
    {
362
        try {
363
            $this->getInstance()->commit();
364
            return true;
365
        } catch (PDOException $e) {
366
            $this->setError($e);
367
        }
368
    }
369
370
    /**
371
     * @return bool|null
372
     *
373
     */
374
    protected function rollBackTransaction(): ?bool
375
    {
376
377
        try {
378
            $this->getInstance()->rollBack();
379
            return true;
380
        } catch (PDOException $e) {
381
            $this->setError($e);
382
        }
383
    }
384
385
    /**
386
     *  @return string|null
387
     *  */
388
    private function lastId(): ?string
389
    {
390
        try {
391
            return $this->getInstance()->lastInsertId();
392
        } catch (PDOException $e) {
393
            $this->setError($e);
394
        }
395
    }
396
397
    /**
398
     * @param $sql_string
399
     * @param array|null $params
400
     * @return void
401
     */
402
    private function setLogSQL($sql_string, ?array $params = null)
403
    {
404
        if (!empty($params)) {
405
            $indexed = $params == array_values($params);
406
            foreach ($params as $k => $v) {
407
                if (is_object($v)) {
408
                    if ($v instanceof \DateTime) {
409
                        $v = $v->format('Y-m-d H:i:s');
410
                    } else {
411
                        continue;
412
                    }
413
                } elseif (is_string($v)) {
414
                    $v = "'$v'";
415
                } elseif ($v === null) {
416
                    $v = 'NULL';
417
                } elseif (is_array($v)) {
418
                    $v = implode(',', $v);
419
                }
420
421
                if ($indexed) {
422
                    $sql_string = preg_replace('/\?/', $v, $sql_string, 1);
423
                } else {
424
                    if ($k[0] != ':') {
425
                        $k = ':' . $k;
426
                    } //add leading colon if it was left out
427
                    $sql_string = str_replace($k, $v, $sql_string);
428
                }
429
            }
430
        }
431
        $this->logSQL = $sql_string;
432
    }
433
434
    /**
435
     * @param PDOException $e
436
     * @return void
437
     */
438
    private function setError(PDOException $e)
439
    {
440
        $this->error = $e;
441
        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

441
        throw new PDOException("{$e->getMessage()}<br/><b>SQL:</b> {$this->/** @scrutinizer ignore-call */ getSQL()}");
Loading history...
442
443
    }
444
}
445