SimplePHP::__callStatic()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 2
dl 0
loc 2
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 SimplePHP\Traits\Properties;
10
use SimplePHP\Model\ChildSimplePHP;
11
use PDO,
12
    PDOException,
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, Properties;
0 ignored issues
show
Bug introduced by
The trait SimplePHP\Traits\Properties requires the property $primaryKey which is not provided by SimplePHP\Model\SimplePHP.
Loading history...
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
    /** @var object|null */
68
    protected $childClass;
69
70
    /** @var array */
71
    private static $reservedWords = ['where', 'find', 'by'];
72
73
    /**
74
     * Get tablename of children model
75
     * @param string|null $tableName
76
     */
77
    function __construct(String $tableName = null, String $primaryKey = null)
78
    {
79
        $this->setRealTable()->setRealPrimary();
80
81
        $this->childClass = new ChildSimplePHP(get_called_class());
82
83
        if($tableName) $this->table = $tableName;
84
85
        if($primaryKey) $this->primary = $primaryKey;
86
    }
87
88
    private function setRealTable() : ?SimplePHP
89
    {
90
        $this->table = $this->getTable() ?? strtolower($this->childClass->realName) . 's';
91
        return $this;
92
    }
93
94
    private function setRealPrimary() : ?SimplePHP
95
    {
96
        $this->primary = $this->getPrimary() ?? 'id';
97
        return $this;
98
    }
99
100
    /**
101
     * @param int|null $id
102
     * @return SimplePHP|null
103
     */
104
    public function find(int $id = null): ?SimplePHP
105
    {
106
        is_int($id) ? $this->where([[$this->primary, '=', $id]]) : null;
107
108
        return $this;
109
    }
110
111
    /**
112
     * @param array $where
113
     * @param string $condition = 'AND'
114
     * @return SimplePHP|null
115
     */
116
    public function where(Array $where, String $condition = 'AND'): ?SimplePHP
117
    {
118
        $this->where = '';
119
        foreach($where as $enclosures) {
120
            $split = isset($enclosures[3]) && !$enclosures[3] ? $enclosures[2] : "'".$enclosures[2]."'";
121
            $this->where .= $enclosures[0]." ".$enclosures[1]." ".$split." {$condition} ";
122
        }
123
        $this->where = "WHERE " . rtrim($this->where, " {$condition} ");
124
125
        return $this;
126
    }
127
128
    /**
129
     * @param array $where
130
     * @return SimplePHP|null
131
     */
132
    public function whereRaw(String $where): ?SimplePHP
133
    {
134
        $this->where = "WHERE " . $where;
135
        return $this;
136
    }
137
138
    /**
139
     * @param array $orWhere
140
     * @param string $condition = 'AND'
141
     * @return SimplePHP|null
142
     */
143
    public function orWhere(Array $orWhere, String $condition = 'AND'): ?SimplePHP
144
    {
145
        $moreWhere = '';
146
        foreach($orWhere as $enclosures) {
147
            $split = isset($enclosures[3]) && !$enclosures[3] ? $enclosures[2] : "'".$enclosures[2]."'";
148
            $moreWhere .= $enclosures[0]." ".$enclosures[1]." ".$split." {$condition} ";
149
        }
150
        $this->where .= " OR " . rtrim($moreWhere, " {$condition} ");
151
152
        return $this;
153
    }
154
155
    /**
156
     * @param array $params
157
     * @return SimplePHP|null
158
     */
159
    public function only(Array $params): ?SimplePHP
160
    {
161
        $this->params = implode(',', $params);
162
        return $this;
163
    }
164
165
    /**
166
     * @param int $limit
167
     * @return SimplePHP|null
168
     */
169
    public function limit(int $limit): ?SimplePHP
170
    {
171
        $this->limit = "LIMIT $limit";
172
        return $this;
173
    }
174
175
    /**
176
     * @param int $offset
177
     * @return SimplePHP|null
178
     */
179
    public function offset(int $offset): ?SimplePHP
180
    {
181
        $this->offset = "OFFSET $offset";
182
        return $this;
183
    }
184
185
    /**
186
     * @param string $order
187
     * @param string $ordenation = 'ASC'
188
     * @return SimplePHP|null
189
     */
190
    public function orderBy(String $prop, String $ordenation = 'ASC'): ?SimplePHP
191
    {
192
        if(mb_strlen($this->order) < 9) {
193
            $this->order = "ORDER BY {$prop} {$ordenation}";
194
        } else {
195
            $this->order .= ", {$prop} {$ordenation}";
196
        }
197
        return $this;
198
    }
199
200
    /**
201
     * @param string $prop
202
     * @return SimplePHP|null
203
     */
204
    public function groupBy(String $prop): ?SimplePHP
205
    {
206
        if(mb_strlen($this->group) < 9) {
207
            $this->group = "GROUP BY {$prop}";
208
        } else {
209
            $this->group .= ", {$prop}";
210
        }
211
        return $this;
212
    }
213
214
    /**
215
     * @param string $name
216
     * @param mixed $arguments
217
     * @return Array|Null|SimplePHP
218
     */
219
    public function __call(String $name, $arguments)
220
    {
221
        if($name === 'skip')
222
            return $this->offset($arguments[0]);
223
224
        if($name === 'take')
225
            return $this->limit($arguments[0]);
226
227
        if($name === 'get')
228
            return $this->execute();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->execute() also could return the type integer which is incompatible with the documented return type SimplePHP\Model\SimplePHP|array|null.
Loading history...
229
230
        if($name === 'first')
231
            return $this->execute(true);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->execute(true) also could return the type integer which is incompatible with the documented return type SimplePHP\Model\SimplePHP|array|null.
Loading history...
232
233
        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...
Bug Best Practice introduced by
The expression return $this->writeLog('...\"<b>'.$name.'</b>\".') returns the type void which is incompatible with the documented return type SimplePHP\Model\SimplePHP|array|null.
Loading history...
234
    }
235
236
    /**
237
     * @param array $deniable
238
     * @return SimplePHP|null
239
     */
240
    public function except(Array $deniable): ?SimplePHP
241
    {
242
        $this->excepts = $deniable;
243
        return $this;
244
    }
245
246
    /**
247
     * @return null
248
     */
249
    private function deny()
250
    {
251
        if (!empty($this->excepts)) {
252
            foreach ($this->excepts as $except) {
253
                if (isset($this->data[$except])) unset($this->data[$except]);
254
            }
255
        }
256
    }
257
258
    /**
259
     * @param $prop
260
     * @param $value
261
     * @return null
262
     */
263
    public function __set($prop, $value)
264
    {
265
        if (empty($this->data)) {
266
            $this->data = new stdClass();
267
        }
268
269
        $this->data->$prop = $value;
270
    }
271
272
    /**
273
     * @param $attribute
274
     * @return bool
275
     */
276
    public function __isset($attribute): bool
277
    {
278
        return isset($this->data->$attribute);
279
    }
280
281
    /**
282
     * @param $prop
283
     * @return string|null
284
     */
285
    public function __get($prop): ?String
286
    {
287
        return $this->data->$prop ?? null;
288
    }
289
290
    public function count(): SimplePHP
291
    {
292
        $this->count = true;
293
        return $this;
294
    }
295
296
    /**
297
     * @return array|object|int|null
298
     */
299
    public function execute(bool $type = false)
300
    {
301
        $this->type = $type;
302
        try {
303
            if(!is_object(Connection::getConnection())) 
304
                return $this->writeLog("Connection failed. Check your connection config and try again.", true);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->writeLog('Connect... and try again.', 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...
305
            
306
            $execute = Connection::getConnection()->query("SELECT {$this->params} FROM {$this->table} {$this->where} {$this->group} {$this->order} {$this->limit} {$this->offset}");
307
            $execute->rowCount() > 1 ? 
308
                    $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));
309
        $this->deny();
310
        return !$this->count ? $this->data : $execute->rowCount();
311
        } catch (PDOException $exc) {
312
            return $this->writeLog($exc->getMessage(), true);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->writeLog($exc->getMessage(), 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...
313
        }
314
    }
315
316
    /**
317
     * @return null|bool
318
     */
319
    public function destroy(): ?bool
320
    {
321
        $primary = $this->primary;
322
        if (!isset($this->data->$primary)) {
323
            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...
Bug Best Practice introduced by
The expression return $this->writeLog('... index was not found.') returns the type void which is incompatible with the type-hinted return boolean|null.
Loading history...
324
        }
325
326
        return $this->delete($this->data->$primary);
327
    }
328
329
    /**
330
     * @return null|bool
331
     */
332
    public function save()
333
    {
334
        $primary = $this->primary;
335
        $data = json_decode(json_encode($this->data), true);
336
        if (empty($primary) || !isset($data[$primary])) {
337
            return $this->writeLog("The primary index was not found.");
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->writeLog('... index was not found.') returns the type void which is incompatible with the documented return type boolean|null.
Loading history...
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...
338
        } else if (!$this->find($data[$primary])->execute()) {
339
            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...
Bug Best Practice introduced by
The expression return $this->writeLog('...ound in the database.') returns the type void which is incompatible with the documented return type boolean|null.
Loading history...
340
        }
341
342
        $otherPrimary = $data[$primary];
343
        unset($data[$primary]);
344
        $parameters = implode(',', array_keys($data));
345
        $values = array_values($data);
346
347
        return $this->update($parameters, $values, $otherPrimary);
348
    }
349
350
    /**
351
     * @return SimplePHP|null
352
     */
353
    public function request(Array $request): ?SimplePHP
354
    {
355
        $this->request = $request;
356
        return $this;
357
    }
358
359
    /**
360
     * @return null|bool
361
     */
362
    public function create(): ?bool
363
    {
364
        $request = $this->request;
365
        if (empty($request)) {
366
            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...
Bug Best Practice introduced by
The expression return $this->writeLog('...was passed to record.') returns the type void which is incompatible with the type-hinted return boolean|null.
Loading history...
367
        }
368
369
        $parameters = implode(',', array_keys($request));
370
        $values = array_values($request);
371
        
372
        return $this->insert($parameters, $values);
373
    }
374
375
    /**
376
     * @param string $message
377
     * @return null|Logger
378
     */
379
    protected function writeLog($message, $pdo = false): void
380
    {
381
        $log = new Logger('SimplePHP');
382
        $log->pushHandler(new StreamHandler(self::$config["pathLog"], Logger::WARNING));
383
384
        if($pdo) {
385
            $log->error($message);
386
            return;
387
        }
388
389
        $log->warning($message);
390
    }
391
392
    /**
393
     * @param string $table
394
     * @return SimplePHP|null
395
     */
396
    public function useTable(String $table): ?SimplePHP
397
    {
398
        $this->table = $table;
399
        return $this;
400
    }
401
402
    /**
403
     * @return string
404
     */
405
    public function debugQuery(): String
406
    {
407
        return "SELECT {$this->params} FROM {$this->table} {$this->where} {$this->group} {$this->order} {$this->limit} {$this->offset}";
408
    }
409
410
    /**
411
     * @return SimplePHP|null
412
     */
413
    public static function __callStatic($name, $arguments)
414
    {
415
        // if($name === 'find')
416
        //     return (new Static)->find($arguments[0])->execute(true);
417
    }
418
419
    /**
420
     * @return SimplePHP|null
421
     */
422
    public static function findByPrimary(Int $id) : ?SimplePHP
423
    {
424
        return (
425
            new static()
426
        )->find($id);
427
    }
428
}