-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass.recordlist.php
More file actions
102 lines (84 loc) · 2.6 KB
/
class.recordlist.php
File metadata and controls
102 lines (84 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
namespace Module\DB;
require_once(dirname(__FILE__) . '/class.record.php');
require_once(dirname(__FILE__) . '/../../core/class.hooks.php');
/**
* Create an iterable list of records
*
* ### Usage
*
* <code>
* $facilities = new \Module\DB\RecordList(new Facility(), 'active=1');
* foreach ($facilities as $f) {
* $f->columns['active'] = 0;
* $f->save();
* }
* </code>
*
* ### Changelog
*
* ## Version 1.0
* *
*
* @section dependencies Dependencies
* * class.hooks.php
* * class.db.php
* * class.record.php
*
* @date May 10, 2019
* @author Jaime A. Rodriguez <jaime@rodriguez-jr.com>
* @version 1.0
* @license http://opensource.org/licenses/MIT
**/
class RecordList extends \ArrayIterator {
/**
* PDO The PDO object
*/
protected $db;
public function __construct(Record $record, string $where = "", array $data = []) {
$this->data = $data;
$items = [];
$this->key = \Sleepy\Hook::addFilter('record_list_key', $record->primaryKey);
$this->table = \Sleepy\Hook::addFilter('record_list_table', $record->table);
$this->where = \Sleepy\Hook::addFilter('record_list_where', $where);
$this->db = DB::getInstance();
if (!empty($this->where)) {
$query = $this->db->prepare("SELECT `{$this->key}` FROM `{$this->table}` WHERE {$this->where}");
} else {
$query = $this->db->prepare("SELECT `{$this->key}` FROM `{$this->table}`");
}
if (count($this->data)) {
$query->execute($this->data);
} else {
$query->execute();
}
$query->setFetchMode(\PDO::FETCH_ASSOC);
foreach ($rows = $query->fetchAll() as $row) {
$instance = clone $record;
$instance->load($row[$this->key]);
\Sleepy\Hook::addFilter("record_list_item", $instance);
array_push($items, $instance);
}
parent::__construct($items);
}
public function getTotal() {
$data = $this->data;
if (!empty($this->where)) {
// We have to remove the offset and limit if they exist
$where = preg_replace('/\s?(LIMIT ?[0-9]*(:limit)?)?\s(OFFSET ?[0-9]*(:offset)?)/i', '', $this->where);
// Drop the data if they exist as well
if (isset($data[':limit'])) unset($data[':limit']);
if (isset($data[':offset'])) unset($data[':offset']);
$query = $this->db->prepare("SELECT count(*) FROM `{$this->table}` WHERE {$where}");
} else {
$query = $this->db->prepare("SELECT count(*) FROM `{$this->table}`");
}
if (count($data)) {
$query->execute($data);
} else {
$query->execute();
}
$results = $query->fetch();
return $results[0];
}
}