Passed
Push — master ( 133bfa...a0084e )
by Nícollas
01:34
created

SimplePHP::whereRaw()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SimplePHP\Model;
4
5
use SimplePHP\Root\{
6
    Connection,
7
    Functions
8
};
9
use PDO,
10
    PDOException,
11
    Exception,
12
    Error,
13
    stdClass;
14
use SimplePHP\Model\CRUD as Actions;
15
use Monolog\Logger;
16
use Monolog\Handler\StreamHandler;
17
18
/**
19
 * Class SimplePHP
20
 * @package NicollasSilva\SimplePHP
21
 */
22
class SimplePHP extends Connection {
23
    use Actions, Functions;
24
25
    /** @var string */
26
    protected $sentence = '';
27
28
    /** @var string */
29
    protected $offset;
30
31
    /** @var string */
32
    protected $order;
33
34
    /** @var string */
35
    protected $params = '*';
36
37
    /** @var string */
38
    protected $where;
39
40
    /** @var string */
41
    protected $limit;
42
43
    /** @var string */
44
    protected $table;
45
46
    /** @var object|null */
47
    protected $data;
48
49
    /** @var bool */
50
    protected $type;
51
52
    /** @var string */
53
    protected $primary;
54
55
    /** @var array */
56
    protected $request = [];
57
58
    /** @var array */
59
    protected $excepts = [];
60
61
    /** @var bool */
62
    protected $count = false;
63
64
    /** @var string */
65
    protected $group;
66
67
    /**
68
     * Get tablename of children model
69
     * @param string|null $tableName
70
     */
71
    function __construct(String $tableName, String $primaryKey)
72
    {
73
        parent::__construct(); $this->table = $tableName; $this->primary = $primaryKey;
74
    }
75
76
    /**
77
     * @param int|null $id
78
     * @return SimplePHP|null
79
     */
80
    public function find(int $id = null): ?SimplePHP
81
    {
82
        is_int($id) ? $this->whereRaw("id = {$id}") : null;
83
        return $this;
84
    }
85
86
    /**
87
     * @param array $where
88
     * @param string $condition = 'AND'
89
     * @return SimplePHP|null
90
     */
91
    public function where(Array $where, String $condition = 'AND'): ?SimplePHP
92
    {
93
        foreach($where as $enclosures) {
94
            $split = isset($enclosures[3]) && !$enclosures[3] ? $enclosures[2] : "'".$enclosures[2]."'";
95
            $this->where .= $enclosures[0]." ".$enclosures[1]." ".$split." {$condition} ";
96
        }
97
        $this->where = "WHERE " . rtrim($this->where, " {$condition} ");
98
99
        return $this;
100
    }
101
102
    /**
103
     * @param array $where
104
     * @return SimplePHP|null
105
     */
106
    public function whereRaw(String $where): ?SimplePHP
107
    {
108
        $this->where = "WHERE " . $where;
109
        return $this;
110
    }
111
112
    /**
113
     * @param array $orWhere
114
     * @param string $condition = 'AND'
115
     * @return SimplePHP|null
116
     */
117
    public function orWhere(Array $orWhere, String $condition = 'AND'): ?SimplePHP
118
    {
119
        $moreWhere = '';
120
        foreach($orWhere as $enclosures) {
121
            $split = isset($enclosures[3]) && !$enclosures[3] ? $enclosures[2] : "'".$enclosures[2]."'";
122
            $moreWhere .= $enclosures[0]." ".$enclosures[1]." ".$split." {$condition} ";
123
        }
124
        $this->where .= " OR " . rtrim($moreWhere, " {$condition} ");
125
126
        return $this;
127
    }
128
129
    /**
130
     * @param array $params
131
     * @return SimplePHP|null
132
     */
133
    public function only(Array $params): ?SimplePHP
134
    {
135
        $this->params = implode($params, ',');
0 ignored issues
show
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

135
        $this->params = /** @scrutinizer ignore-call */ implode($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...
136
        return $this;
137
    }
138
139
    /**
140
     * @param int $limit
141
     * @return SimplePHP|null
142
     */
143
    public function limit(int $limit): ?SimplePHP
144
    {
145
        $this->limit = "LIMIT $limit";
146
        return $this;
147
    }
148
149
    /**
150
     * @param int $offset
151
     * @return SimplePHP|null
152
     */
153
    public function offset(int $offset): ?SimplePHP
154
    {
155
        $this->offset = "OFFSET $offset";
156
        return $this;
157
    }
158
159
    /**
160
     * @param string $order
161
     * @param string $ordenation = 'ASC'
162
     * @return SimplePHP|null
163
     */
164
    public function orderBy(String $prop, String $ordenation = 'ASC'): ?SimplePHP
165
    {
166
        if(mb_strlen($this->order) < 9) {
167
            $this->order = "ORDER BY {$prop} {$ordenation}";
168
        } else {
169
            $this->order .= ", {$prop} {$ordenation}";
170
        }
171
        return $this;
172
    }
173
174
    /**
175
     * @param string $prop
176
     * @return SimplePHP|null
177
     */
178
    public function groupBy(String $prop): ?SimplePHP
179
    {
180
        if(mb_strlen($this->group) < 9) {
181
            $this->group = "GROUP BY {$prop}";
182
        } else {
183
            $this->group .= ", {$prop}";
184
        }
185
        return $this;
186
    }
187
188
    /**
189
     * @param string $name
190
     * @param mixed $arguments
191
     * @return null
192
     */
193
    public function __call(String $name, $arguments)
194
    {
195
        if($name === 'skip')
196
            return $this->offset($arguments[0]);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->offset($arguments[0]) returns the type SimplePHP\Model\SimplePHP which is incompatible with the documented return type null.
Loading history...
197
198
        if($name === 'take')
199
            return $this->limit($arguments[0]);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->limit($arguments[0]) returns the type SimplePHP\Model\SimplePHP which is incompatible with the documented return type null.
Loading history...
200
201
        return $this->writeLog("This method does not exist at the SimplePHP: \"<b>{$name}</b>\".");
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->writeLog('This me...\"<b>'.$name.'</b>\".') targeting SimplePHP\Model\SimplePHP::writeLog() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
202
    }
203
204
    /**
205
     * @param array $deniable
206
     * @return SimplePHP|null
207
     */
208
    public function except(Array $deniable)
209
    {
210
        $this->excepts = $deniable;
211
        return $this;
212
    }
213
214
    /**
215
     * @return null
216
     */
217
    private function deny()
218
    {
219
        if (!empty($this->excepts)) {
220
            foreach ($this->excepts as $except) {
221
                if (isset($this->data[$except])) unset($this->data[$except]);
222
            }
223
        }
224
    }
225
226
    /**
227
     * @param $prop
228
     * @param $value
229
     * @return null
230
     */
231
    public function __set($prop, $value)
232
    {
233
        if (empty($this->data)) {
234
            $this->data = new stdClass();
235
        }
236
237
        $this->data->$prop = $value;
238
    }
239
240
    /**
241
     * @param $attribute
242
     * @return bool
243
     */
244
    public function __isset($attribute): bool
245
    {
246
        return isset($this->data->$attribute);
247
    }
248
249
    /**
250
     * @param $prop
251
     * @return string|null
252
     */
253
    public function __get($prop)
254
    {
255
        return $this->data->$prop ?? null;
256
    }
257
258
    public function count(): SimplePHP
259
    {
260
        $this->count = true;
261
        return $this;
262
    }
263
264
    /**
265
     * @return array|object|int|null
266
     */
267
    public function execute(bool $type = false)
268
    {
269
        $this->type = $type;
270
        try {
271
            $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

271
            /** @scrutinizer ignore-call */ 
272
            $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...
272
            $execute->rowCount() > 1 ? 
273
                    $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));
274
        $this->deny();
275
        return !$this->count ? $this->data : $execute->rowCount();
276
        } catch (PDOException $exc) {
277
            return $this->writeLog($exc->getCode(), true);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->writeLog($exc->getCode(), true) targeting SimplePHP\Model\SimplePHP::writeLog() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
278
        }
279
    }
280
281
    /**
282
     * @return null|bool
283
     */
284
    public function destroy()
285
    {
286
        $primary = $this->primary;
287
        if (!isset($this->data->$primary)) {
288
            return $this->writeLog("The primary index was not found.");
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->writeLog('The pri... index was not found.') targeting SimplePHP\Model\SimplePHP::writeLog() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
289
        }
290
291
        return $this->delete($this->data->$primary);
292
    }
293
294
    /**
295
     * @return null|bool
296
     */
297
    public function save()
298
    {
299
        $primary = $this->primary;
300
        $data = json_decode(json_encode($this->data), true);
301
        if (empty($primary) || !isset($data[$primary])) {
302
            return $this->writeLog("The primary index was not found.");
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->writeLog('The pri... index was not found.') targeting SimplePHP\Model\SimplePHP::writeLog() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
303
        } else if (!$this->find($data[$primary])->execute()) {
304
            return $this->writeLog("The primary index was not found in the database.");
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->writeLog('The pri...ound in the database.') targeting SimplePHP\Model\SimplePHP::writeLog() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
305
        }
306
307
        $otherPrimary = $data[$primary];
308
        unset($data[$primary]);
309
        $parameters = implode(',', array_keys($data));
310
        $values = array_values($data);
311
312
        return $this->update($parameters, $values, $otherPrimary);
313
    }
314
315
    /**
316
     * @return SimplePHP|null
317
     */
318
    public function request(Array $request): ?SimplePHP
319
    {
320
        $this->request = $request;
321
        return $this;
322
    }
323
324
    /**
325
     * @return null|bool
326
     */
327
    public function create()
328
    {
329
        $request = $this->request;
330
        if (empty($request)) {
331
            return $this->writeLog("No information was passed to record.");
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->writeLog('No info...was passed to record.') targeting SimplePHP\Model\SimplePHP::writeLog() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
332
        }
333
334
        $parameters = implode(',', array_keys($request));
335
        $values = array_values($request);
336
        
337
        return $this->insert($parameters, $values);
338
    }
339
340
    /**
341
     * @param string $message
342
     * @return null|Logger
343
     */
344
    protected function writeLog($message, $pdo = false): ?Logger
345
    {
346
        $log = new Logger('SimplePHP');
347
        $log->pushHandler(new StreamHandler($this->config["pathLog"], Logger::WARNING));
348
        $pdo ? $log->error($message) : $log->warning($message);
349
        return null;
350
    }
351
352
    /**
353
     * @param string $table
354
     * @return SimplePHP|null
355
     */
356
    public function useTable(String $table): ?SimplePHP
357
    {
358
        $this->table = $table;
359
        return $this;
360
    }
361
362
    /**
363
     * @return string
364
     */
365
    public function debugQuery()
366
    {
367
        return "SELECT {$this->params} FROM {$this->table} {$this->where} {$this->group} {$this->order} {$this->limit} {$this->offset}";
368
    }
369
}