Passed
Push — master ( 268116...cc8508 )
by Nícollas
01:20
created

SimplePHP::error()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 1
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 2
rs 10
1
<?php
2
3
namespace SimplePHP\Model;
4
5
use SimplePHP\Root\Connection;
6
use PDO;
7
use PDOException;
8
use Error;
9
use stdClass;
10
use SimplePHP\Model\CRUD as Actions;
11
12
/**
13
 * Class SimplePHP
14
 * @package NicollasSilva\SimplePHP
15
 */
16
class SimplePHP extends Connection {
17
    use Actions;
18
19
    /** @var string */
20
    protected $sentence = '';
21
22
    /** @var string */
23
    protected $offset;
24
25
    /** @var string */
26
    protected $order;
27
28
    /** @var string */
29
    protected $params = '*';
30
31
    /** @var string */
32
    protected $where;
33
34
    /** @var string */
35
    protected $limit;
36
37
    /** @var string */
38
    protected $table;
39
40
    /** @var object|null */
41
    protected $data;
42
43
    /** @var bool */
44
    protected $type;
45
46
    /** @var array */
47
    protected $excepts = [];
48
49
    /** @var string */
50
    protected $primary;
51
52
    /** @var array */
53
    protected $request = [];
54
55
    /**
56
     * Get tablename of children model
57
     * @param string|null $tableName
58
     */
59
    function __construct(?string $tableName, ?string $primaryKey)
60
    {
61
        parent::__construct(); $this->table = $tableName; $this->primary = $primaryKey;
62
    }
63
64
    /**
65
     * @param int|null $id
66
     * @return SimplePHP|null
67
     */
68
    public function find(?int $id = null): ?SimplePHP
69
    {
70
        is_int($id) ? self::where('id', $id) : null;
0 ignored issues
show
Bug Best Practice introduced by
The method SimplePHP\Model\SimplePHP::where() is not static, but was called statically. ( Ignorable by Annotation )

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

70
        is_int($id) ? self::/** @scrutinizer ignore-call */ where('id', $id) : null;
Loading history...
71
        return $this;
72
    }
73
74
    /**
75
     * @param string $condition
76
     * @param string $value
77
     * @return SimplePHP|null
78
     */
79
    public function where(string $condition, string $value): ?SimplePHP
80
    {
81
        $this->where = "WHERE " . (mb_strlen($this->where > 6) ? "&& {$condition} = '{$value}'" : "{$condition} = '{$value}'");
82
        return $this;
83
    }
84
85
    /**
86
     * @param array $params
87
     * @return SimplePHP|null
88
     */
89
    public function only(array $params): ?SimplePHP
90
    {
91
        $params !== null ? $this->params = implode($params, ',') : $this->params = '*';
0 ignored issues
show
introduced by
The condition $params !== null is always true.
Loading history...
Unused Code introduced by
The call to implode() has too many arguments starting with ','. ( Ignorable by Annotation )

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

91
        $params !== null ? $this->params = /** @scrutinizer ignore-call */ implode($params, ',') : $this->params = '*';

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...
92
        return $this;
93
    }
94
95
    /**
96
     * @param int $limit
97
     * @return SimplePHP|null
98
     */
99
    public function limit(int $limit): ?SimplePHP
100
    {
101
        $this->limit = "LIMIT $limit";
102
        return $this;
103
    }
104
105
    /**
106
     * @param int $offset
107
     * @return SimplePHP|null
108
     */
109
    public function offset(int $offset): ?SimplePHP
110
    {
111
        $this->offset = "OFFSET $offset";
112
        return $this;
113
    }
114
115
    /**
116
     * @param string $order
117
     * @return SimplePHP|null
118
     */
119
    public function orderBy(string $order): ?SimplePHP
120
    {
121
        $this->order = "ORDER BY {$order}";
122
        return $this;
123
    }
124
125
    /**
126
     * @param string $name
127
     * @param mixed $arguments
128
     * @return string error
129
     */
130
    public function __call(string $name, $arguments)
131
    {
132
        return "This method does not exist at the SimplePHP: \"<b>{$name}</b>\".";
133
    }
134
135
    /**
136
     * @param array $deniable
137
     * @return SimplePHP|null
138
     */
139
    public function except(array $deniable)
140
    {
141
        $this->excepts = $deniable;
142
        return $this;
143
    }
144
145
    /**
146
     * @param $prop
147
     * @param $value
148
     * @return null
149
     */
150
    public function __set($prop, $value)
151
    {
152
        if (empty($this->data)) {
153
            $this->data = new stdClass();
154
        }
155
156
        $this->data->$prop = $value;
157
    }
158
159
    /**
160
     * @param $attribute
161
     * @return bool
162
     */
163
    public function __isset($attribute): bool
164
    {
165
        return isset($this->data->$attribute);
166
    }
167
168
    /**
169
     * @param $prop
170
     * @return string|null
171
     */
172
    public function __get($prop)
173
    {
174
        return $this->data->$prop ?? null;
175
    }
176
177
    /**
178
     * Method to destroy @except method
179
     */
180
    private function deny()
181
    {
182
        if(!empty($this->excepts)) {
183
            switch (!is_object($this->data) && $count = count($this->data)) {
184
                case (!isset($this->data[0]) && !empty($this->data)):
185
                    foreach($this->excepts as $except) {
186
                        if(isset($this->data[$except])) {
187
                            unset($this->data[$except]);
188
                        }
189
                    }
190
                    break;
191
                case ($count >= 2 && isset($this->data[0])):
192
                    foreach($this->excepts as $except) {
193
                        for($i = 0; $i < $count; $i++) {
194
                            if(isset($this->data[$i][$except])) {
195
                                unset($this->data[$i][$except]);
196
                            }
197
                        }
198
                    }
199
                    break;
200
                default:
201
                    return [];
202
            }
203
        }
204
    }
205
206
    /**
207
     * @return array|mixed
208
     */
209
    public function execute(bool $type = false)
210
    {
211
        $this->type = $type;
212
        try {
213
            $execute = $this->conn->query("SELECT {$this->params} FROM {$this->table} {$this->where} {$this->order} {$this->limit} {$this->offset}");
0 ignored issues
show
Bug introduced by
The method query() 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

213
            /** @scrutinizer ignore-call */ 
214
            $execute = $this->conn->query("SELECT {$this->params} FROM {$this->table} {$this->where} {$this->order} {$this->limit} {$this->offset}");

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...
214
            $execute->rowCount() > 1 ? 
215
                    $this->data = ($this->type ? $execute->fetchAll(PDO::FETCH_CLASS, static::class) : $execute->fetchAll(PDO::FETCH_ASSOC)) : $this->data = ($this->type ? $execute->fetchObject(static::class) : $execute->fetch(PDO::FETCH_ASSOC));
216
            $this->deny();
217
            return $this->data;
218
        } catch (PDOException $exc) {
219
            return $exc->getMessage();
220
        }
221
    }
222
223
    /**
224
     * @return Exception|bool(true)
0 ignored issues
show
Bug introduced by
The type SimplePHP\Model\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
225
     */
226
    public function destroy()
227
    {
228
        $primary = $this->primary;
229
        if (!isset($this->data->$primary)) {
230
            $this->error("Índice primário não encontrado: {$primary}.", __FUNCTION__);
231
        }
232
233
        return $this->delete($this->data->$primary);
234
    }
235
236
    /**
237
     * @return Error|bool
238
     */
239
    public function save()
240
    {
241
        $primary = $this->primary;
242
        $data = json_decode(json_encode($this->data), true);
243
        if (empty($primary) || !isset($data[$primary])) {
244
            $this->error("Índice primário não encontrado: {$primary}.", __FUNCTION__);
245
        } else if(!$this->find($data[$primary])->execute()) {
246
            $this->error("Esse registro não consta no banco de dados: {$data[$primary]}.", __FUNCTION__);
247
        }
248
249
        $otherPrimary = $data[$primary];
250
        unset($data[$primary]);
251
        $parameters = implode(',', array_keys($data));
252
        $values = array_values($data);
253
254
        return $this->update($parameters, $values, $otherPrimary);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->update($pa...$values, $otherPrimary) also could return the type PDOException which is incompatible with the documented return type Error|boolean.
Loading history...
255
    }
256
257
    /**
258
     * @return SimplePHP|null
259
     */
260
    public function request(Array $request): ?SimplePHP
261
    {
262
        $this->request = $request;
263
        return $this;
264
    }
265
266
    /**
267
     * @return PDOException|Error|bool
268
     */
269
    public function create()
270
    {
271
        $request = $this->request;
272
        if(empty($request)) {
273
            $this->error("O array request está vazio!", __FUNCTION__);
274
        }
275
276
        $parameters = implode(',', array_keys($request));
277
        $values = array_values($request);
278
        
279
        return $this->insert($parameters, $values);
280
    }
281
282
    /**
283
     * @param string $message
284
     * @param string $function
285
     * @return Error|null
286
     */
287
    public function error(String $message, String $function): ?Error {
288
        if($message) { throw new Error($message." Método: ".strtoupper($function)); } else { return null; };
289
    }
290
}