Passed
Push — main ( 15d6bc...51062a )
by BRUNO
01:53
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
    protected $instance = null;
23
24
    /** @var string */
25
    protected $fields;
26
27
    /** @var PDOStatement|null */
28
    protected $prepare = null;
29
30
    /** @var string */
31
    protected $database = CONFIG_DATA_LAYER["dbname"];
32
33
    /** @var string */
34
    protected $classModel;
35
36
    /** @var string */
37
    protected $tableName;
38
39
    /** @var string */
40
    private $tableAlias;
41
42
    /** @var array */
43
    protected $resultArray = array();
44
45
    /** @var string */
46
    private $logSQL;
47
48
    /** @var PDOException */
49
    private $error;
50
51
    /** @var string */
52
    private $query = "";
53
54
    /** @var array */
55
    private $params = [];
56
57
    private QueryBuilder $queryBuild;
58
59
60
    /** @return PDO|false */
61
    private function getInstance()
62
    {
63
        try {
64
            if (strpos($_SERVER['SERVER_NAME'], mb_strtolower(CONFIG_DATA_LAYER["homologation"])) && !strpos($this->database, ucfirst(CONFIG_DATA_LAYER["homologation"]))) {
65
                $this->database .= ucfirst(CONFIG_DATA_LAYER["homologation"] ?? "");
66
            }
67
68
            if (empty($this->instance)) {
69
                $this->instance = new PDO(
70
                    CONFIG_DATA_LAYER['driver'] . ':host=' . CONFIG_DATA_LAYER['host'] . ';dbname=' . $this->database . ';port=' . CONFIG_DATA_LAYER['port'],
71
                    CONFIG_DATA_LAYER['username'],
72
                    CONFIG_DATA_LAYER['passwd'],
73
                    CONFIG_DATA_LAYER['options']
74
                );
75
            }
76
77
            return $this->instance;
78
        } catch (PDOException $e) {
79
            $this->setError($e);
80
        }
81
82
    }
83
84
    /**
85
     * @param PDO $pdo
86
     * @return Crud
87
     *
88
     */
89
    protected function setInstance(PDO $pdo)
90
    {
91
        $this->instance = $pdo;
92
        return $this;
93
    }
94
95
    /**
96
     * @param string $database
97
     * @return $this
98
     */
99
    protected function setDatabase(string $database)
100
    {
101
        $this->database = $database;
102
        return $this;
103
    }
104
105
    /**
106
     * @return string
107
     */
108
    protected function getDatabase(): string
109
    {
110
        return $this->database;
111
    }
112
113
    /**
114
     * @param string $tableName
115
     * @return Crud
116
     */
117
    protected function setFields(string $fields)
118
    {
119
        $this->fields = $fields;
120
        return $this;
121
    }
122
123
    /**
124
     * @return string
125
     */
126
    protected function getFields():string
127
    {
128
        return $this->fields;
129
    }
130
131
    /**
132
     * @param string $tableName
133
     * @return Crud
134
     */
135
    protected function setTable(string $tableName, string $tableAlias = ""): self
136
    {
137
        if (!empty($tableAlias))
138
            $this->tableAlias = $tableAlias;
139
        $this->tableName = $tableName;
140
        return $this;
141
    }
142
143
    /**
144
     * @return string
145
     */
146
    protected function getTable(): string
147
    {
148
        return $this->tableName;
149
    }
150
151
    public function getQueryBuilder(): QueryBuilder
152
    {
153
        if (!empty($this->queryBuild))
154
            return $this->queryBuild;
155
        return new QueryBuilder($this->getInstance(), $this->getTable(), $this->getClassModel());
156
    }
157
158
    public  function getTableAlias(): string
159
    {
160
        return $this->tableAlias;
161
    }
162
163
    /**
164
     * @param string $classModel
165
     * @return Crud
166
     */
167
    protected function setClassModel(string $classModel): self
168
    {
169
        $this->classModel = $classModel;
170
        return $this;
171
    }
172
173
    protected function getClassModel()
174
    {
175
        return $this->classModel;
176
    }
177
178
    /**
179
     * @param String $query
180
     * @param array|null $params
181
     * @return false|mixed|\PDOStatement|null
182
     */
183
    protected function executeSQL(string $query, ?array $params = null)
184
    {
185
        try {
186
            $this->prepare = $this->getInstance()->prepare($query);
187
            $this->setLogSQL($query, $params);
188
            $this->prepare->execute($params);
189
            return $this->prepare;
190
        } catch (PDOException $e) {
191
            $this->setError($e);
192
        }
193
    }
194
195
    /**
196
     * @param $prepare
197
     * @return int|false
198
     */
199
    protected function count(PDOStatement $prepare = null): ?int
200
    {
201
        try {
202
            $prepare = empty($prepare) ? $this->prepare : $prepare;
203
            return $prepare->rowCount();
0 ignored issues
show
Bug introduced by
The method rowCount() does not exist on null. ( Ignorable by Annotation )

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

203
            return $prepare->/** @scrutinizer ignore-call */ rowCount();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

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

405
        throw new PDOException("{$e->getMessage()}<br/><b>SQL:</b> {$this->/** @scrutinizer ignore-call */ getLogSQL()}");
Loading history...
406
407
    }
408
}
409