Passed
Push — main ( 7c0f98...efcfe1 )
by BRUNO
01:59
created

DatalayerTrait::setTable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 6
rs 10
c 2
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
    protected 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 getInstance()
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->getInstance())) {
80
                $instance = new PDO(
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
                $this->setInstance($instance);
87
            }
88
89
            return $this->getInstance();
90
        } catch (PDOException $e) {
91
            $this->setError($e);
92
        }
93
94
    }
95
96
    /**
97
     * @param ?PDO $pdo
98
     * @return Crud
99
     *
100
     */
101
    protected function setInstance(?PDO $pdo): self
102
    {
103
        $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

103
        /** @scrutinizer ignore-deprecated */ $this->instance = $pdo;
Loading history...
104
        return $this;
105
    }
106
107
    /**
108
     * @param string $database
109
     * @return $this
110
     */
111
    protected function setDatabase(string $database): self
112
    {
113
        $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

113
        /** @scrutinizer ignore-deprecated */ $this->database = $database;
Loading history...
114
        $this->setInstance(null);
115
        return $this;
116
    }
117
118
    /**
119
     * @return string
120
     */
121
    protected function getDatabase(): string
122
    {
123
        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

123
        return /** @scrutinizer ignore-deprecated */ $this->database ?? "";
Loading history...
124
    }
125
126
    /**
127
     * @param string $fields
128
     * @return Crud
129
     */
130
    protected function setFields(string $fields): self
131
    {
132
        $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

132
        /** @scrutinizer ignore-deprecated */ $this->fields = $fields;
Loading history...
133
        return $this;
134
    }
135
136
    /**
137
     * @return string
138
     */
139
    protected function getFields():string
140
    {
141
        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

141
        return /** @scrutinizer ignore-deprecated */ $this->fields;
Loading history...
142
    }
143
144
    /**
145
        * @param string $tableName
146
        * @param string $tableAlias
147
        * @return CrudBuilder|Crud|DatalayerTrait
148
     */
149
    protected function setTable(string $tableName, string $tableAlias = ""): self
150
    {
151
        if (!empty($tableAlias))
152
            $this->tableAlias = $tableAlias;
153
        $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

153
        /** @scrutinizer ignore-deprecated */ $this->tableName = $tableName;
Loading history...
154
        return $this;
155
    }
156
157
    /**
158
     * @return string
159
     */
160
    protected function getTable(): string
161
    {
162
        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

162
        return /** @scrutinizer ignore-deprecated */ $this->tableName ?? "";
Loading history...
163
    }
164
165
    protected function getTableAlias(): string
166
    {
167
        return $this->tableAlias ?? "";
168
    }
169
170
    /**
171
     * @param string $classModel
172
     * @return Crud
173
     */
174
    protected function setClassModel(string $classModel): self
175
    {
176
        $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

176
        /** @scrutinizer ignore-deprecated */ $this->classModel = $classModel;
Loading history...
177
        return $this;
178
    }
179
180
    protected function getClassModel(): string
181
    {
182
        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

182
        return /** @scrutinizer ignore-deprecated */ $this->classModel;
Loading history...
183
    }
184
185
    /**
186
     * @param string $classModel
187
     * @return Crud
188
     */
189
    protected function setPrepare(PDOStatement $prepare): self
190
    {
191
        $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

191
        /** @scrutinizer ignore-deprecated */ $this->prepare = $prepare;
Loading history...
192
        return $this;
193
    }
194
195
    protected function getPrepare(): PDOStatement
196
    {
197
        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

197
        return /** @scrutinizer ignore-deprecated */ $this->prepare;
Loading history...
198
    }
199
200
    protected function getResult(): array
201
    {
202
       return $this->resultArray;
203
    }
204
205
    protected function setResult(array $array): self
206
    {
207
        $this->resultArray = $array;
208
        return $this;
209
    }
210
211
    /**
212
        * @param string $query
213
        * @param array|null $params
214
        * @return PDOStatement|void
215
     */
216
    protected function executeSQL(string $query, ?array $params = null)
217
    {
218
        try {
219
            $this->setPrepare($this->getInstance()->prepare($query));
220
            $this->setLogSQL($query, $params);
221
            $this->getPrepare()->execute($params);
222
            return $this->getPrepare();
223
        } catch (PDOException $e) {
224
            $this->setError($e);
225
        }
226
    }
227
228
    /**
229
     * @param $prepare
230
     * @return int|false
231
     */
232
    protected function count(PDOStatement $prepare = null): ?int
233
    {
234
        try {
235
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
236
            return $prepare->rowCount();
237
        } catch (PDOException $e) {
238
            $this->setError($e);}
239
    }
240
241
    /**
242
    * @param PDOStatement|null $prepare
243
    * @return array|null
244
     */
245
    protected function fetchArrayAssoc(PDOStatement $prepare = null): ?array
246
    {
247
        try {
248
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
249
            $dados = $prepare->fetchAll(PDO::FETCH_ASSOC);
250
            $this->setResult($dados);
251
            return $dados;
252
        } catch (PDOException $e) {
253
            $this->setError($e);
254
        }
255
    }
256
257
    /**
258
     * @param $prepare
259
     * @return array|false
260
     */
261
    protected function fetchArrayObj(PDOStatement $prepare = null): ?array
262
    {
263
        try {
264
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
265
            $dados = $prepare->fetchAll(PDO::FETCH_OBJ);
266
            $this->setResult($dados);
267
            return $dados;
268
        } catch (PDOException $e) {
269
            $this->setError($e);
270
        }
271
    }
272
273
    /**
274
     * @param $prepare
275
     * @param String|null $classModel
276
     * @return array|false
277
     */
278
    protected function fetchArrayClass(PDOStatement $prepare = null, string $classModel = null): ?array
279
    {
280
        try {
281
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
282
            $classModel = empty($classModel) ? $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

282
            $classModel = empty($classModel) ? /** @scrutinizer ignore-deprecated */ $this->classModel : $classModel;
Loading history...
283
            $dados = $prepare->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, CONFIG_DATA_LAYER["directory_models"] . $classModel);
284
            $this->setResult($dados);
285
            return $dados;
286
        } catch (PDOException $e) {
287
            $this->setError($e);
288
        }
289
    }
290
291
    /**
292
     * @param $prepare
293
     * @return array|false
294
     */
295
    protected function fetchOneAssoc(PDOStatement $prepare = null): ?array
296
    {
297
        try {
298
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
299
            return $prepare->fetch(PDO::FETCH_ASSOC);
300
        } catch (PDOException $e) {
301
            $this->setError($e);
302
        }
303
    }
304
305
    /**
306
    * @param PDOStatement|null $prepare
307
    * @return stdClass|null
308
     */
309
    protected function fetchOneObj(PDOStatement $prepare = null): ?stdClass
310
    {
311
        try {
312
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
313
            return $prepare->fetch(PDO::FETCH_OBJ);
314
        } catch (PDOException $e) {
315
            $this->setError($e);
316
        }
317
    }
318
319
    /**
320
     * @param $prepare
321
     * @param String|null $class
322
     * @return array|false
323
     */
324
    protected function fetchOneClass(PDOStatement $prepare = null, string $class = null): ?object
325
    {
326
        try {
327
            $prepare = empty($prepare) ? $this->getPrepare() : $prepare;
328
            $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

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

433
        throw new PDOException("{$e->getMessage()}<br/><b>SQL:</b> {$this->/** @scrutinizer ignore-call */ getSQL()}");
Loading history...
434
435
    }
436
}
437