Passed
Push — main ( 8ecc9d...1ce003 )
by BRUNO
02:00
created

DatalayerTrait::getQueryBuilder()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 5
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
58
    /** @return PDO|false */
59
    private function getInstance()
60
    {
61
        try {
62
            if (strpos($_SERVER['SERVER_NAME'], mb_strtolower(CONFIG_DATA_LAYER["homologation"])) && !strpos($this->database, ucfirst(CONFIG_DATA_LAYER["homologation"]))) {
63
                $this->database .= ucfirst(CONFIG_DATA_LAYER["homologation"] ?? "");
64
            }
65
66
            if (empty($this->instance)) {
67
                $this->instance = new PDO(
68
                    CONFIG_DATA_LAYER['driver'] . ':host=' . CONFIG_DATA_LAYER['host'] . ';dbname=' . $this->database . ';port=' . CONFIG_DATA_LAYER['port'],
69
                    CONFIG_DATA_LAYER['username'],
70
                    CONFIG_DATA_LAYER['passwd'],
71
                    CONFIG_DATA_LAYER['options']
72
                );
73
            }
74
75
            return $this->instance;
76
        } catch (PDOException $e) {
77
            $this->setError($e);
78
        }
79
80
    }
81
82
    /**
83
     * @param PDO $pdo
84
     * @return Crud
85
     *
86
     */
87
    protected function setInstance(PDO $pdo)
88
    {
89
        $this->instance = $pdo;
90
        return $this;
91
    }
92
93
    /**
94
     * @param string $database
95
     * @return $this
96
     */
97
    protected function setDatabase(string $database)
98
    {
99
        $this->database = $database;
100
        return $this;
101
    }
102
103
    /**
104
     * @return string
105
     */
106
    protected function getDatabase(): string
107
    {
108
        return $this->database;
109
    }
110
111
    /**
112
     * @param string $tableName
113
     * @return Crud
114
     */
115
    protected function setFields(string $fields)
116
    {
117
        $this->fields = $fields;
118
        return $this;
119
    }
120
121
    /**
122
     * @return string
123
     */
124
    protected function getFields():string
125
    {
126
        return $this->fields;
127
    }
128
129
    /**
130
     * @param string $tableName
131
     * @return Crud
132
     */
133
    protected function setTable(string $tableName, string $tableAlias = ""): self
134
    {
135
        if (!empty($tableAlias))
136
            $this->tableAlias = $tableAlias;
137
        $this->tableName = $tableName;
138
        return $this;
139
    }
140
141
    /**
142
     * @return string
143
     */
144
    protected function getTable(): string
145
    {
146
        return $this->tableName;
147
    }
148
149
    public  function getTableAlias(): string
150
    {
151
        return $this->tableAlias;
152
    }
153
154
    /**
155
     * @param string $classModel
156
     * @return Crud
157
     */
158
    protected function setClassModel(string $classModel): self
159
    {
160
        $this->classModel = $classModel;
161
        return $this;
162
    }
163
164
    protected function getClassModel()
165
    {
166
        return $this->classModel;
167
    }
168
169
    /**
170
     * @param String $query
171
     * @param array|null $params
172
     * @return false|mixed|\PDOStatement|null
173
     */
174
    protected function executeSQL(string $query, ?array $params = null)
175
    {
176
        try {
177
            $this->prepare = $this->getInstance()->prepare($query);
178
            $this->setLogSQL($query, $params);
179
            $this->prepare->execute($params);
180
            return $this->prepare;
181
        } catch (PDOException $e) {
182
            $this->setError($e);
183
        }
184
    }
185
186
    /**
187
     * @param $prepare
188
     * @return int|false
189
     */
190
    protected function count(PDOStatement $prepare = null): ?int
191
    {
192
        try {
193
            $prepare = empty($prepare) ? $this->prepare : $prepare;
194
            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

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

396
        throw new PDOException("{$e->getMessage()}<br/><b>SQL:</b> {$this->/** @scrutinizer ignore-call */ getLogSQL()}");
Loading history...
397
398
    }
399
}
400