Issues (994)

src/DB/DB.php (10 issues)

1
<?php
2
3
namespace DB;
4
5
use ArrayAccess;
6
use MVC\Exception;
7
use PDO;
0 ignored issues
show
This use statement conflicts with another class in this namespace, DB\PDO. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
8
9
/**
10
 * Simple PDO.
11
 *
12
 * @see https://github.com/mareimorsy/DB
13
 */
14
class DB
15
{
16
  private static $instance = null;
17
  private $dbh = null;
18
  private $table;
19
  private $columns;
20
  private $sql;
21
  private $bindValues;
22
  private $getSQL;
23
  private $where;
24
  private $orWhere;
25
  private $whereCount = 0;
26
  private $isOrWhere = false;
27
  private $rowCount = 0;
28
  private $limit;
29
  private $orderBy;
30
  private $lastIDInserted = 0;
31
32
  // Initial values for pagination array
33
  private $pagination = ['previousPage' => null, 'currentPage' => 1, 'nextPage' => null, 'lastPage' => null, 'totalRows' => null];
34
35
  private function __construct($config = ['host' => '', 'database' => '', 'username' => '', 'password' => ''])
36
  {
37
    try {
38
      $this->dbh = new PDO('mysql:host=' . $config['host'] . ';dbname=' . $config['database'] . ';charset=utf8', $config['username'], $config['password']);
39
      $this->dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
40
    } catch (Exception $e) {
41
      die('Error establishing a database connection.');
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
42
    }
43
  }
44
45
  public static function getInstance($config = ['host' => '', 'database' => '', 'username' => '', 'password' => ''])
46
  {
47
    if (!self::$instance) {
48
      self::$instance = new DB($config);
49
    }
50
51
    return self::$instance;
52
  }
53
54
  public function query($query, $args = [], $quick = false)
55
  {
56
    $this->resetQuery();
57
    $query = trim($query);
58
    $this->getSQL = $query;
59
    $this->bindValues = $args;
60
61
    if (true == $quick) {
62
      $stmt = $this->dbh->prepare($query);
63
      $stmt->execute($this->bindValues);
64
      $this->rowCount = $stmt->rowCount();
65
66
      return $stmt->fetchAll();
67
    } else {
68
      if (0 === strpos(strtoupper($query), 'SELECT')) {
69
        $stmt = $this->dbh->prepare($query);
70
        $stmt->execute($this->bindValues);
71
        $this->rowCount = $stmt->rowCount();
72
73
        $rows = $stmt->fetchAll(PDO::FETCH_CLASS, 'MareiObj');
74
        $collection = [];
0 ignored issues
show
The assignment to $collection is dead and can be removed.
Loading history...
75
        $collection = new MareiCollection();
76
        $x = 0;
77
        foreach ($rows as $key => $row) {
78
          $collection->offsetSet($x++, $row);
79
        }
80
81
        return $collection;
82
      } else {
83
        $this->getSQL = $query;
84
        $stmt = $this->dbh->prepare($query);
85
        $stmt->execute($this->bindValues);
86
87
        return $stmt->rowCount();
88
      }
89
    }
90
  }
91
92
  public function exec()
93
  {
94
    //assimble query
95
    $this->sql .= $this->where;
96
    $this->getSQL = $this->sql;
97
    $stmt = $this->dbh->prepare($this->sql);
98
    $stmt->execute($this->bindValues);
99
100
    return $stmt->rowCount();
101
  }
102
103
  private function resetQuery()
104
  {
105
    $this->table = null;
106
    $this->columns = null;
107
    $this->sql = null;
108
    $this->bindValues = null;
109
    $this->limit = null;
110
    $this->orderBy = null;
111
    $this->getSQL = null;
112
    $this->where = null;
113
    $this->orWhere = null;
114
    $this->whereCount = 0;
115
    $this->isOrWhere = false;
116
    $this->rowCount = 0;
117
    $this->lastIDInserted = 0;
118
  }
119
120
  public function delete($table_name, $id = null)
121
  {
122
    $this->resetQuery();
123
124
    $this->sql = "DELETE FROM `{$table_name}`";
125
126
    if (isset($id)) {
127
      // if there is an ID
128
      if (is_numeric($id)) {
129
        $this->sql .= ' WHERE `id` = ?';
130
        $this->bindValues[] = $id;
131
      // if there is an Array
132
      } elseif (is_array($id)) {
133
        $arr = $id;
134
        $count_arr = count($arr);
0 ignored issues
show
The assignment to $count_arr is dead and can be removed.
Loading history...
135
        $x = 0;
136
137
        foreach ($arr as  $param) {
138
          if (0 == $x) {
139
            $this->where .= ' WHERE ';
140
            ++$x;
141
          } else {
142
            if ($this->isOrWhere) {
143
              $this->where .= ' Or ';
144
            } else {
145
              $this->where .= ' AND ';
146
            }
147
148
            ++$x;
149
          }
150
          $count_param = count($param);
151
152
          if (1 == $count_param) {
153
            $this->where .= '`id` = ?';
154
            $this->bindValues[] = $param[0];
155
          } elseif (2 == $count_param) {
156
            $operators = explode(',', '=,>,<,>=,>=,<>');
157
            $operatorFound = false;
158
159
            foreach ($operators as $operator) {
160
              if (false !== strpos($param[0], $operator)) {
161
                $operatorFound = true;
162
                break;
163
              }
164
            }
165
166
            if ($operatorFound) {
167
              $this->where .= $param[0] . ' ?';
168
            } else {
169
              $this->where .= '`' . trim($param[0]) . '` = ?';
170
            }
171
172
            $this->bindValues[] = $param[1];
173
          } elseif (3 == $count_param) {
174
            $this->where .= '`' . trim($param[0]) . '` ' . $param[1] . ' ?';
175
            $this->bindValues[] = $param[2];
176
          }
177
        }
178
        //end foreach
179
      }
180
      // end if there is an Array
181
      $this->sql .= $this->where;
182
183
      $this->getSQL = $this->sql;
184
      $stmt = $this->dbh->prepare($this->sql);
185
      $stmt->execute($this->bindValues);
186
187
      return $stmt->rowCount();
188
    } // end if there is an ID or Array
189
    // $this->getSQL = "<b>Attention:</b> This Query will update all rows in the table, luckily it didn't execute yet!, use exec() method to execute the following query :<br>". $this->sql;
190
    // $this->getSQL = $this->sql;
191
    return $this;
192
  }
193
194
  public function update($table_name, $fields = [], $id = null)
195
  {
196
    $this->resetQuery();
197
    $set = '';
198
    $x = 1;
199
200
    foreach ($fields as $column => $field) {
201
      $set .= "`$column` = ?";
202
      $this->bindValues[] = $field;
203
      if ($x < count($fields)) {
204
        $set .= ', ';
205
      }
206
      ++$x;
207
    }
208
209
    $this->sql = "UPDATE `{$table_name}` SET $set";
210
211
    if (isset($id)) {
212
      // if there is an ID
213
      if (is_numeric($id)) {
214
        $this->sql .= ' WHERE `id` = ?';
215
        $this->bindValues[] = $id;
216
      // if there is an Array
217
      } elseif (is_array($id)) {
218
        $arr = $id;
219
        $count_arr = count($arr);
0 ignored issues
show
The assignment to $count_arr is dead and can be removed.
Loading history...
220
        $x = 0;
221
222
        foreach ($arr as  $param) {
223
          if (0 == $x) {
224
            $this->where .= ' WHERE ';
225
            ++$x;
226
          } else {
227
            if ($this->isOrWhere) {
228
              $this->where .= ' Or ';
229
            } else {
230
              $this->where .= ' AND ';
231
            }
232
233
            ++$x;
234
          }
235
          $count_param = count($param);
236
237
          if (1 == $count_param) {
238
            $this->where .= '`id` = ?';
239
            $this->bindValues[] = $param[0];
240
          } elseif (2 == $count_param) {
241
            $operators = explode(',', '=,>,<,>=,>=,<>');
242
            $operatorFound = false;
243
244
            foreach ($operators as $operator) {
245
              if (false !== strpos($param[0], $operator)) {
246
                $operatorFound = true;
247
                break;
248
              }
249
            }
250
251
            if ($operatorFound) {
252
              $this->where .= $param[0] . ' ?';
253
            } else {
254
              $this->where .= '`' . trim($param[0]) . '` = ?';
255
            }
256
257
            $this->bindValues[] = $param[1];
258
          } elseif (3 == $count_param) {
259
            $this->where .= '`' . trim($param[0]) . '` ' . $param[1] . ' ?';
260
            $this->bindValues[] = $param[2];
261
          }
262
        }
263
        //end foreach
264
      }
265
      // end if there is an Array
266
      $this->sql .= $this->where;
267
268
      $this->getSQL = $this->sql;
269
      $stmt = $this->dbh->prepare($this->sql);
270
      $stmt->execute($this->bindValues);
271
272
      return $stmt->rowCount();
273
    } // end if there is an ID or Array
274
    // $this->getSQL = "<b>Attention:</b> This Query will update all rows in the table, luckily it didn't execute yet!, use exec() method to execute the following query :<br>". $this->sql;
275
    // $this->getSQL = $this->sql;
276
    return $this;
277
  }
278
279
  public function insert($table_name, $fields = [])
280
  {
281
    $this->resetQuery();
282
283
    $keys = implode('`, `', array_keys($fields));
284
    $values = '';
285
    $x = 1;
286
    foreach ($fields as $field => $value) {
287
      $values .= '?';
288
      $this->bindValues[] = $value;
289
      if ($x < count($fields)) {
290
        $values .= ', ';
291
      }
292
      ++$x;
293
    }
294
295
    $this->sql = "INSERT INTO `{$table_name}` (`{$keys}`) VALUES ({$values})";
296
    $this->getSQL = $this->sql;
297
    $stmt = $this->dbh->prepare($this->sql);
298
    $stmt->execute($this->bindValues);
299
    $this->lastIDInserted = $this->dbh->lastInsertId();
300
301
    return $this->lastIDInserted;
302
  }
303
304
  //End insert function
305
306
  public function lastId()
307
  {
308
    return $this->lastIDInserted;
309
  }
310
311
  public function table($table_name)
312
  {
313
    $this->resetQuery();
314
    $this->table = $table_name;
315
316
    return $this;
317
  }
318
319
  public function select($columns)
320
  {
321
    $columns = explode(',', $columns);
322
    foreach ($columns as $key => $column) {
323
      $columns[$key] = trim($column);
324
    }
325
326
    $columns = implode('`, `', $columns);
327
328
    $this->columns = "`{$columns}`";
329
330
    return $this;
331
  }
332
333
  public function where()
334
  {
335
    if (0 == $this->whereCount) {
336
      $this->where .= ' WHERE ';
337
      ++$this->whereCount;
338
    } else {
339
      $this->where .= ' AND ';
340
    }
341
342
    $this->isOrWhere = false;
343
344
    // call_user_method_array('where_orWhere', $this, func_get_args());
345
    //Call to undefined function call_user_method_array()
346
    //echo print_r(func_num_args());
347
    $num_args = func_num_args();
348
    $args = func_get_args();
349
    if (1 == $num_args) {
350
      if (is_numeric($args[0])) {
351
        $this->where .= '`id` = ?';
352
        $this->bindValues[] = $args[0];
353
      } elseif (is_array($args[0])) {
354
        $arr = $args[0];
355
        $count_arr = count($arr);
0 ignored issues
show
The assignment to $count_arr is dead and can be removed.
Loading history...
356
        $x = 0;
357
358
        foreach ($arr as  $param) {
359
          if (0 == $x) {
360
            ++$x;
361
          } else {
362
            if ($this->isOrWhere) {
363
              $this->where .= ' Or ';
364
            } else {
365
              $this->where .= ' AND ';
366
            }
367
368
            ++$x;
369
          }
370
          $count_param = count($param);
371
          if (1 == $count_param) {
372
            $this->where .= '`id` = ?';
373
            $this->bindValues[] = $param[0];
374
          } elseif (2 == $count_param) {
375
            $operators = explode(',', '=,>,<,>=,>=,<>');
376
            $operatorFound = false;
377
378
            foreach ($operators as $operator) {
379
              if (false !== strpos($param[0], $operator)) {
380
                $operatorFound = true;
381
                break;
382
              }
383
            }
384
385
            if ($operatorFound) {
386
              $this->where .= $param[0] . ' ?';
387
            } else {
388
              $this->where .= '`' . trim($param[0]) . '` = ?';
389
            }
390
391
            $this->bindValues[] = $param[1];
392
          } elseif (3 == $count_param) {
393
            $this->where .= '`' . trim($param[0]) . '` ' . $param[1] . ' ?';
394
            $this->bindValues[] = $param[2];
395
          }
396
        }
397
      }
398
      // end of is array
399
    } elseif (2 == $num_args) {
400
      $operators = explode(',', '=,>,<,>=,>=,<>');
401
      $operatorFound = false;
402
      foreach ($operators as $operator) {
403
        if (false !== strpos($args[0], $operator)) {
404
          $operatorFound = true;
405
          break;
406
        }
407
      }
408
409
      if ($operatorFound) {
410
        $this->where .= $args[0] . ' ?';
411
      } else {
412
        $this->where .= '`' . trim($args[0]) . '` = ?';
413
      }
414
415
      $this->bindValues[] = $args[1];
416
    } elseif (3 == $num_args) {
417
      $this->where .= '`' . trim($args[0]) . '` ' . $args[1] . ' ?';
418
      $this->bindValues[] = $args[2];
419
    }
420
421
    return $this;
422
  }
423
424
  public function orWhere()
425
  {
426
    if (0 == $this->whereCount) {
427
      $this->where .= ' WHERE ';
428
      ++$this->whereCount;
429
    } else {
430
      $this->where .= ' OR ';
431
    }
432
    $this->isOrWhere = true;
433
    // call_user_method_array ( 'where_orWhere' , $this ,  func_get_args() );
434
435
    $num_args = func_num_args();
436
    $args = func_get_args();
437
    if (1 == $num_args) {
438
      if (is_numeric($args[0])) {
439
        $this->where .= '`id` = ?';
440
        $this->bindValues[] = $args[0];
441
      } elseif (is_array($args[0])) {
442
        $arr = $args[0];
443
        $count_arr = count($arr);
0 ignored issues
show
The assignment to $count_arr is dead and can be removed.
Loading history...
444
        $x = 0;
445
446
        foreach ($arr as  $param) {
447
          if (0 == $x) {
448
            ++$x;
449
          } else {
450
            if ($this->isOrWhere) {
451
              $this->where .= ' Or ';
452
            } else {
453
              $this->where .= ' AND ';
454
            }
455
456
            ++$x;
457
          }
458
          $count_param = count($param);
459
          if (1 == $count_param) {
460
            $this->where .= '`id` = ?';
461
            $this->bindValues[] = $param[0];
462
          } elseif (2 == $count_param) {
463
            $operators = explode(',', '=,>,<,>=,>=,<>');
464
            $operatorFound = false;
465
466
            foreach ($operators as $operator) {
467
              if (false !== strpos($param[0], $operator)) {
468
                $operatorFound = true;
469
                break;
470
              }
471
            }
472
473
            if ($operatorFound) {
474
              $this->where .= $param[0] . ' ?';
475
            } else {
476
              $this->where .= '`' . trim($param[0]) . '` = ?';
477
            }
478
479
            $this->bindValues[] = $param[1];
480
          } elseif (3 == $count_param) {
481
            $this->where .= '`' . trim($param[0]) . '` ' . $param[1] . ' ?';
482
            $this->bindValues[] = $param[2];
483
          }
484
        }
485
      }
486
      // end of is array
487
    } elseif (2 == $num_args) {
488
      $operators = explode(',', '=,>,<,>=,>=,<>');
489
      $operatorFound = false;
490
      foreach ($operators as $operator) {
491
        if (false !== strpos($args[0], $operator)) {
492
          $operatorFound = true;
493
          break;
494
        }
495
      }
496
497
      if ($operatorFound) {
498
        $this->where .= $args[0] . ' ?';
499
      } else {
500
        $this->where .= '`' . trim($args[0]) . '` = ?';
501
      }
502
503
      $this->bindValues[] = $args[1];
504
    } elseif (3 == $num_args) {
505
      $this->where .= '`' . trim($args[0]) . '` ' . $args[1] . ' ?';
506
      $this->bindValues[] = $args[2];
507
    }
508
509
    return $this;
510
  }
511
512
  // private function where_orWhere()
513
  // {
514
515
  // }
516
517
  public function get()
518
  {
519
    $this->assimbleQuery();
520
    $this->getSQL = $this->sql;
521
522
    $stmt = $this->dbh->prepare($this->sql);
523
    $stmt->execute($this->bindValues);
524
    $this->rowCount = $stmt->rowCount();
525
526
    $rows = $stmt->fetchAll(PDO::FETCH_CLASS, 'MareiObj');
527
    $collection = [];
0 ignored issues
show
The assignment to $collection is dead and can be removed.
Loading history...
528
    $collection = new MareiCollection();
529
    $x = 0;
530
    foreach ($rows as $key => $row) {
531
      $collection->offsetSet($x++, $row);
532
    }
533
534
    return $collection;
535
  }
536
537
  // Quick get
538
  public function QGet()
539
  {
540
    $this->assimbleQuery();
541
    $this->getSQL = $this->sql;
542
543
    $stmt = $this->dbh->prepare($this->sql);
544
    $stmt->execute($this->bindValues);
545
    $this->rowCount = $stmt->rowCount();
546
547
    return $stmt->fetchAll();
548
  }
549
550
  private function assimbleQuery()
551
  {
552
    if (null !== $this->columns) {
553
      $select = $this->columns;
554
    } else {
555
      $select = '*';
556
    }
557
558
    $this->sql = "SELECT $select FROM `$this->table`";
559
560
    if (null !== $this->where) {
561
      $this->sql .= $this->where;
562
    }
563
564
    if (null !== $this->orderBy) {
565
      $this->sql .= $this->orderBy;
566
    }
567
568
    if (null !== $this->limit) {
569
      $this->sql .= $this->limit;
570
    }
571
  }
572
573
  public function limit($limit, $offset = null)
574
  {
575
    if (null == $offset) {
576
      $this->limit = " LIMIT {$limit}";
577
    } else {
578
      $this->limit = " LIMIT {$limit} OFFSET {$offset}";
579
    }
580
581
    return $this;
582
  }
583
584
  /**
585
   * Sort result in a particular order according to a column name.
586
   *
587
   * @param string $field_name the column name which you want to order the result according to
588
   * @param string $order      it determins in which order you wanna view your results whether 'ASC' or 'DESC'
589
   *
590
   * @return object it returns DB object
591
   */
592
  public function orderBy($field_name, $order = 'ASC')
593
  {
594
    $field_name = trim($field_name);
595
596
    $order = trim(strtoupper($order));
597
598
    // validate it's not empty and have a proper valuse
599
    if (null !== $field_name && ('ASC' == $order || 'DESC' == $order)) {
600
      if (null == $this->orderBy) {
601
        $this->orderBy = " ORDER BY $field_name $order";
602
      } else {
603
        $this->orderBy .= ", $field_name $order";
604
      }
605
    }
606
607
    return $this;
608
  }
609
610
  public function paginate($page, $limit)
611
  {
612
    // Start assimble Query
613
    $countSQL = "SELECT COUNT(*) FROM `$this->table`";
614
    if (null !== $this->where) {
615
      $countSQL .= $this->where;
616
    }
617
    // Start assimble Query
618
619
    $stmt = $this->dbh->prepare($countSQL);
620
    $stmt->execute($this->bindValues);
621
    $totalRows = $stmt->fetch(PDO::FETCH_NUM)[0];
622
    // echo $totalRows;
623
624
    $offset = ($page - 1) * $limit;
625
    // Refresh Pagination Array
626
    $this->pagination['currentPage'] = $page;
627
    $this->pagination['lastPage'] = ceil($totalRows / $limit);
628
    $this->pagination['nextPage'] = $page + 1;
629
    $this->pagination['previousPage'] = $page - 1;
630
    $this->pagination['totalRows'] = $totalRows;
631
    // if last page = current page
632
    if ($this->pagination['lastPage'] == $page) {
633
      $this->pagination['nextPage'] = null;
634
    }
635
    if (1 == $page) {
636
      $this->pagination['previousPage'] = null;
637
    }
638
    if ($page > $this->pagination['lastPage']) {
639
      return [];
640
    }
641
642
    $this->assimbleQuery();
643
644
    $sql = $this->sql . " LIMIT {$limit} OFFSET {$offset}";
645
    $this->getSQL = $sql;
646
647
    $stmt = $this->dbh->prepare($sql);
648
    $stmt->execute($this->bindValues);
649
    $this->rowCount = $stmt->rowCount();
650
651
    $rows = $stmt->fetchAll(PDO::FETCH_CLASS, 'MareiObj');
652
    $collection = [];
0 ignored issues
show
The assignment to $collection is dead and can be removed.
Loading history...
653
    $collection = new MareiCollection();
654
    $x = 0;
655
    foreach ($rows as $key => $row) {
656
      $collection->offsetSet($x++, $row);
657
    }
658
659
    return $collection;
660
  }
661
662
  public function count()
663
  {
664
    // Start assimble Query
665
    $countSQL = "SELECT COUNT(*) FROM `$this->table`";
666
667
    if (null !== $this->where) {
668
      $countSQL .= $this->where;
669
    }
670
671
    if (null !== $this->limit) {
672
      $countSQL .= $this->limit;
673
    }
674
    // End assimble Query
675
676
    $stmt = $this->dbh->prepare($countSQL);
677
    $stmt->execute($this->bindValues);
678
679
    $this->getSQL = $countSQL;
680
681
    return $stmt->fetch(PDO::FETCH_NUM)[0];
682
  }
683
684
  public function QPaginate($page, $limit)
685
  {
686
    // Start assimble Query
687
    $countSQL = "SELECT COUNT(*) FROM `$this->table`";
688
    if (null !== $this->where) {
689
      $countSQL .= $this->where;
690
    }
691
    // Start assimble Query
692
693
    $stmt = $this->dbh->prepare($countSQL);
694
    $stmt->execute($this->bindValues);
695
    $totalRows = $stmt->fetch(PDO::FETCH_NUM)[0];
696
    // echo $totalRows;
697
698
    $offset = ($page - 1) * $limit;
699
    // Refresh Pagination Array
700
    $this->pagination['currentPage'] = $page;
701
    $this->pagination['lastPage'] = ceil($totalRows / $limit);
702
    $this->pagination['nextPage'] = $page + 1;
703
    $this->pagination['previousPage'] = $page - 1;
704
    $this->pagination['totalRows'] = $totalRows;
705
    // if last page = current page
706
    if ($this->pagination['lastPage'] == $page) {
707
      $this->pagination['nextPage'] = null;
708
    }
709
    if (1 == $page) {
710
      $this->pagination['previousPage'] = null;
711
    }
712
    if ($page > $this->pagination['lastPage']) {
713
      return [];
714
    }
715
716
    $this->assimbleQuery();
717
718
    $sql = $this->sql . " LIMIT {$limit} OFFSET {$offset}";
719
    $this->getSQL = $sql;
720
721
    $stmt = $this->dbh->prepare($sql);
722
    $stmt->execute($this->bindValues);
723
    $this->rowCount = $stmt->rowCount();
724
725
    return $stmt->fetchAll();
726
  }
727
728
  public function PaginationInfo()
729
  {
730
    return $this->pagination;
731
  }
732
733
  public function getSQL()
734
  {
735
    return $this->getSQL;
736
  }
737
738
  public function getCount()
739
  {
740
    return $this->rowCount;
741
  }
742
743
  public function rowCount()
744
  {
745
    return $this->rowCount;
746
  }
747
}
748
// End Marei DB Class
749
750
//Start Marei Object Class
751
class MareiObj
752
{
753
  public function toJSON()
754
  {
755
    return json_encode($this, JSON_NUMERIC_CHECK);
756
  }
757
758
  public function toArray()
759
  {
760
    return (array) $this;
761
  }
762
763
  public function __toString()
764
  {
765
    header('Content-Type: application/json;charset=utf-8');
766
767
    return json_encode($this, JSON_NUMERIC_CHECK);
768
  }
769
}
770
// End Marei Object Class
771
772
//Start Marei collection class
773
class MareiCollection implements ArrayAccess
774
{
775
  public function offsetSet($offset, $value)
776
  {
777
    $this->$offset = $value;
778
  }
779
780
  public function toJSON()
781
  {
782
    return json_encode($this->toArray(), JSON_NUMERIC_CHECK);
783
  }
784
785
  public function toArray()
786
  {
787
    // return (array) get_object_vars($this);
788
    $array = [];
789
    foreach ($this as  $mareiObj) {
790
      $array[] = (array) $mareiObj;
791
    }
792
793
    return $array;
794
  }
795
796
  public function list($field)
797
  {
798
    $list = [];
799
    foreach ($this as  $item) {
800
      $list[] = $item->{$field};
801
    }
802
803
    return $list;
804
  }
805
806
  public function first($offset = 0)
807
  {
808
    return isset($this->$offset) ? $this->$offset : null;
809
  }
810
811
  public function last($offset = null)
0 ignored issues
show
The parameter $offset is not used and could be removed. ( Ignorable by Annotation )

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

811
  public function last(/** @scrutinizer ignore-unused */ $offset = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
812
  {
813
    $offset = count($this->toArray()) - 1;
814
815
    return isset($this->$offset) ? $this->$offset : null;
816
  }
817
818
  public function offsetExists($offset)
819
  {
820
    return isset($this->$offset);
821
  }
822
823
  public function offsetUnset($offset)
824
  {
825
    unset($this->$offset);
826
  }
827
828
  public function offsetGet($offset)
829
  {
830
    return isset($this->$offset) ? $this->$offset : null;
831
  }
832
833
  public function item($key)
834
  {
835
    return isset($this->$key) ? $this->$key : null;
836
  }
837
838
  public function __toString()
839
  {
840
    header('Content-Type: application/json;charset=utf-8');
841
    // return json_encode(get_object_vars($this));
842
    return  $this->toJSON();
843
  }
844
}
845
// End Marei Collection Class
846