Passed
Push — main ( 9d8bac...887c45 )
by BRUNO
03:04
created

DatalayerTrait::setLogSQL()   B

Complexity

Conditions 10
Paths 2

Size

Total Lines 30
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

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

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
    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 array */
40
    protected $resultArray = array();
41
42
    /** @var string */
43
    private $logSQL;
44
45
    /** @var PDOException */
46
    private $error;
47
48
    /** @return PDO|false */
49
    private function getInstance()
50
    {
51
        try {
52
            if (strpos($_SERVER['SERVER_NAME'], mb_strtolower(CONFIG_DATA_LAYER["homologation"])) && !strpos($this->database, ucfirst(CONFIG_DATA_LAYER["homologation"]))) {
53
                $this->database .= ucfirst(CONFIG_DATA_LAYER["homologation"] ?? "");
54
            }
55
56
            if (empty($this->instance)) {
57
                $this->instance = new PDO(
58
                    CONFIG_DATA_LAYER['driver'] . ':host=' . CONFIG_DATA_LAYER['host'] . ';dbname=' . $this->database . ';port=' . CONFIG_DATA_LAYER['port'],
59
                    CONFIG_DATA_LAYER['username'],
60
                    CONFIG_DATA_LAYER['passwd'],
61
                    CONFIG_DATA_LAYER['options']
62
                );
63
            }
64
65
            return $this->instance;
66
        } catch (PDOException $e) {
67
            $this->setError($e);
68
        }
69
70
    }
71
72
    /**
73
     * @param PDO $pdo
74
     * @return void
75
     *
76
     * */
77
    protected function setInstance(PDO $pdo)
78
    {
79
        $this->instance = $pdo;
80
    }
81
82
    protected function setDatabase(string $database)
83
    {
84
        $this->database = $database;
85
    }
86
87
    /**
88
     * @return string
89
     */
90
    protected function getDatabase(): string
91
    {
92
        return $this->database;
93
    }
94
95
    /**
96
     * @param string $tableName
97
     * @return void
98
     */
99
    protected function setFields(string $fields)
100
    {
101
        $this->fields = $fields;
102
    }
103
104
    /**
105
     * @param string $tableName
106
     * @return void
107
     */
108
    protected function getFields():string
109
    {
110
        return $this->fields;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->fields returns the type string which is incompatible with the documented return type void.
Loading history...
111
    }
112
113
    /**
114
     * @param string $tableName
115
     * @return void
116
     */
117
    protected function setTable(string $tableName)
118
    {
119
        $this->tableName = $tableName;
120
    }
121
122
    /**
123
     * @param string $tableName
124
     * @return void
125
     */
126
    protected function getTable(): string
127
    {
128
        return $this->tableName;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->tableName returns the type string which is incompatible with the documented return type void.
Loading history...
129
    }
130
131
    /**
132
     * @param string $classModel
133
     * @return void
134
     */
135
    protected function setClassModel(string $classModel)
136
    {
137
        $this->classModel = $classModel;
138
    }
139
140
    /**
141
     * @param String $query
142
     * @param array|null $params
143
     * @return false|mixed|\PDOStatement|null
144
     */
145
    protected function executeSQL(string $query, ?array $params = null)
146
    {
147
        try {
148
            $this->prepare = $this->getInstance()->prepare($query);
149
            $this->setLogSQL($query, $params);
150
            $this->prepare->execute($params);
151
            return $this->prepare;
152
        } catch (PDOException $e) {
153
            $this->setError($e);
154
        }
155
    }
156
157
    /**
158
     * @param $prepare
159
     * @return int|false
160
     */
161
    protected function count(PDOStatement $prepare = null): ?int
162
    {
163
        try {
164
            $prepare = empty($prepare) ? $this->prepare : $prepare;
165
            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

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

366
        throw new PDOException("{$e->getMessage()}<br/><b>SQL:</b> {$this->/** @scrutinizer ignore-call */ getLogSQL()}");
Loading history...
367
368
    }
369
}
370