Passed
Push — main ( 0cf401...c49a8e )
by BRUNO
01:47
created

DatalayerTrait::fetchOneAssoc()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 4
nop 1
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
namespace BMorais\Database;
3
/**
4
 * CLASSE TRAIT DO DATABASE
5
 *  Esta classe de métodos de execução no banco
6
 *
7
 * @author Bruno Morais <[email protected]>
8
 * @copyright GPL © 2022, bmorais.com
9
 * @package bmorais\database
10
 * @subpackage class
11
 * @access private
12
 */
13
14
use PDO;
15
use PDOException;
16
use stdClass;
17
18
19
trait DatalayerTrait
20
{
21
    /** @var PDO */
22
    protected $instance;
23
    protected $params;
24
    protected $prepare = null;
25
    protected $database = CONFIG_DATA_LAYER["dbname"];
26
    protected $classModel;
27
    protected $tableName;
28
    protected $resultArray = array();
29
30
    private $logSQL;
31
32
    /**
33
     * @return PDO|null
34
     */
35
    private function getInstance(): ?PDO
36
    {
37
        if (strpos($_SERVER['SERVER_NAME'], "homologacao") && !strpos($this->database, "Homologacao") )
38
            $this->database .= "Homologacao";
39
40
        if (!isset($this->instance)) {
41
            $this->instance = Connect::getInstance($this->database);
42
            return $this->instance;
43
        } else {
44
            return $this->instance;
45
        }
46
    }
47
48
    /**
49
     * @param String $query
50
     * @param array|null $params
51
     * @return false|mixed|\PDOStatement|null
52
     */
53
    protected function executeSQL(String $query, ?array $params = null)
54
    {
55
        try {
56
            $this->getInstance();
57
            $this->prepare = $this->instance->prepare($query);
58
            $this->prepare->execute($params);
59
            $this->setLogSQL($query, $params);
60
        } catch (PDOException $e) {
61
            Connect::setError($e,$query);
62
            return false;
63
        }
64
65
        return $this->prepare;
66
    }
67
68
    /**
69
     * @param $prepare
70
     * @return int
71
     */
72
    protected function count($prepare=null): int
73
    {
74
        try {
75
            $prepare = empty($prepare) ? $this->prepare : $prepare;
76
            $qtd = $prepare->rowCount();
77
            return $qtd;
78
        } catch (PDOException $e) {
79
            Connect::setError($e);
80
            return false;
81
        }
82
83
84
    }
85
86
    /**
87
     * @param $prepare
88
     * @return array|false
89
     */
90
    protected function fetchArrayAssoc($prepare=null): array
91
    {
92
        try {
93
            $prepare = empty($prepare) ? $this->prepare : $prepare;
94
            $dados = $prepare->fetchAll(PDO::FETCH_ASSOC);
95
            $this->resultArray = $dados;
96
            return $dados;
97
        } catch (PDOException $e) {
98
            Connect::setError($e);
99
            return false;
100
        }
101
    }
102
103
    /**
104
     * @param $prepare
105
     * @return array|false
106
     */
107
    protected function fetchArrayObj($prepare=null): array
108
    {
109
        try {
110
            $prepare = empty($prepare) ? $this->prepare : $prepare;
111
            $dados = $prepare->fetchAll(PDO::FETCH_OBJ);
112
            $this->resultArray = $dados;
113
            return $dados;
114
        } catch (PDOException $e) {
115
            Connect::setError($e);
116
            return false;
117
        }
118
    }
119
120
    /**
121
     * @param $prepare
122
     * @param String|null $class
123
     * @return array|false
124
     */
125
    protected function fetchArrayClass($prepare=null, String $class=null): array
126
    {
127
        try {
128
            $prepare = empty($prepare) ? $this->prepare : $prepare;
129
            $class = empty($class) ? $this->classModel : $class;
130
            $dados = $prepare->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, CONFIG_DATA_LAYER["directory_models"] . $class);
131
            $this->resultArray = $dados;
132
            return $dados;
133
        } catch (PDOException $e) {
134
            Connect::setError($e);
135
            return false;
136
        }
137
    }
138
139
    /**
140
     * @param $prepare
141
     * @return array|false
142
     */
143
    protected function fetchOneAssoc($prepare=null): array
144
    {
145
        try {
146
            $prepare = empty($prepare) ? $this->prepare : $prepare;
147
            $dados = $prepare->fetch(PDO::FETCH_ASSOC);
148
            return $dados;
149
        } catch (PDOException $e) {
150
            Connect::setError($e);
151
            return false;
152
        }
153
    }
154
155
    /**
156
     * @param $prepare
157
     * @return stdClass|false
158
     */
159
    protected function fetchOneObj($prepare=null): stdClass
160
    {
161
        try {
162
            $prepare = empty($prepare) ? $this->prepare : $prepare;
163
            $dados = $prepare->fetch(PDO::FETCH_OBJ);
164
            return $dados;
165
        } catch (PDOException $e) {
166
            Connect::setError($e);
167
            return false;
168
        }
169
    }
170
171
    /**
172
     * @param $prepare
173
     * @param String|null $class
174
     * @return array|false
175
     */
176
    protected function fetchOneClass($prepare=null, String $class=null): object
177
    {
178
        try {
179
            $prepare = empty($prepare) ? $this->prepare : $prepare;
180
            $class = empty($class) ? $this->classModel : $class;
181
            $dados = $prepare->fetchObject(CONFIG_DATA_LAYER["directory_models"] . $class);
182
            return $dados;
183
        } catch (PDOException $e) {
184
            Connect::setError($e);
185
            return false;
186
        }
187
    }
188
189
    /**
190
     * @return bool
191
     */
192
    protected function beginTrasaction(): bool
193
    {
194
        try {
195
            $this->getInstance();
196
            $this->instance->beginTransaction();
197
            return true;
198
        } catch (PDOException $e) {
199
            Connect::setError($e);
200
            return false;
201
        }
202
203
    }
204
205
    /**
206
     * @return bool
207
     */
208
    protected function commitTransaction(): bool
209
    {
210
        try {
211
            $this->getInstance();
212
            $this->instance->commit();
213
            return true;
214
        } catch (PDOException $e) {
215
            Connect::setError($e);
216
            return false;
217
        }
218
    }
219
220
    /**
221
     * @return bool
222
     */
223
    protected function rollBackTransaction(): bool
224
    {
225
226
        try {
227
            $this->getInstance();
228
            $this->instance->rollBack();
229
            return true;
230
        } catch (PDOException $e) {
231
            Connect::setError($e);
232
            return false;
233
        }
234
    }
235
236
    /**
237
    * RETORNAR O ULTIMO ID INSERIDO
238
    */
239
    private function lastId()
240
    {
241
        $this->getInstance();
242
        $ultimo = $this->instance->lastInsertId();
243
        return $ultimo;
244
245
    }
246
247
    /**
248
     * @return array
249
     */
250
    protected function printErrorInfo(): array
251
    {
252
        return $this->getInstance($this->database)->errorInfo();
0 ignored issues
show
Unused Code introduced by
The call to BMorais\Database\DatalayerTrait::getInstance() has too many arguments starting with $this->database. ( Ignorable by Annotation )

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

252
        return $this->/** @scrutinizer ignore-call */ getInstance($this->database)->errorInfo();

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
253
    }
254
255
    /**
256
     * @param $sql_string
257
     * @param array|null $params
258
     * @return void
259
     */
260
    function setLogSQL($sql_string, array $params = null) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
261
        if (!empty($params)) {
262
            $indexed = $params == array_values($params);
263
            foreach($params as $k=>$v) {
264
                if (is_object($v)) {
265
                    if ($v instanceof \DateTime) $v = $v->format('Y-m-d H:i:s');
266
                    else continue;
267
                }
268
                elseif (is_string($v)) $v="'$v'";
269
                elseif ($v === null) $v='NULL';
270
                elseif (is_array($v)) $v = implode(',', $v);
271
272
                if ($indexed) {
273
                    $sql_string = preg_replace('/\?/', $v, $sql_string, 1);
274
                }
275
                else {
276
                    if ($k[0] != ':') $k = ':'.$k; //add leading colon if it was left out
277
                    $sql_string = str_replace($k,$v,$sql_string);
278
                }
279
            }
280
        }
281
        $this->logSQL = $sql_string;
282
    }
283
}
284