-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModelIterator.php
More file actions
124 lines (112 loc) · 2.61 KB
/
Copy pathModelIterator.php
File metadata and controls
124 lines (112 loc) · 2.61 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?php
/**
* This Software is part of aryelgois/Medools and is provided "as is".
*
* @see LICENSE
*/
namespace aryelgois\Medools;
use aryelgois\Utils;
/**
* Easily iterate over different rows of a model
*
* @author Aryel Mota Góis
* @license MIT
* @link https://www.github.com/aryelgois/Medools
*/
class ModelIterator implements \Iterator, \Countable
{
/**
* List PRIMARY KEYS for $model_class
*
* @var mixed[]
*/
protected $list;
/**
* A model to load data from Database, with one item in $list at time
*
* @var string
*/
protected $model_class;
/**
* The current PRIMARY KEY to be used from $list
*
* @var integer
*/
protected $pointer;
/**
* Creates a new Model Iterator
*
* - You provide a Fully Qualified Model Class and a Medoo $where
* - It loads instances of that model class matching $where
* - Now you can iterate over Database rows for that model, one at time
*
* EXAMPLE:
* $class = 'aryelgois\\Medools\\Models\\Person';
* foreach (new ModelIterator($class, ['id[>=]' => 1]) as $model) {
* // code...
* }
*
* @see https://medoo.in/api/where
*
* @param string $model A Fully Qualified Model Class to iterate
* @param mixed[] $where \Medoo\Medoo where clause
*/
public function __construct(string $model_class, $where = [])
{
$this->model_class = $model_class;
$this->list = $model_class::dump($where, $model_class::PRIMARY_KEY);
}
/**
* Counts how many Models are in this Iterator
*
* @return int
*/
public function count()
{
return count($this->list);
}
/**
* Loads the model with the current pointened PRIMARY KEY and returns it
*
* @return Model
*/
public function current()
{
return ModelManager::getInstance(
$this->model_class,
$this->list[$this->pointer]
);
}
/**
* Returns the index for the current PRIMARY KEY in the $list
*
* @return integer
*/
public function key()
{
return $this->pointer;
}
/**
* Forwards the pointer by one
*/
public function next()
{
$this->pointer++;
}
/**
* Resets the pointer to the beginning of the $list
*/
public function rewind()
{
$this->pointer = 0;
}
/**
* Checks if the current pointer is in the $list
*
* @return boolean
*/
public function valid()
{
return isset($this->list[$this->pointer]);
}
}