1 | <?php |
||
7 | abstract class ModelCollection implements CreatableFromArray, \Countable, \Iterator |
||
8 | { |
||
9 | /** |
||
10 | * @var array |
||
11 | */ |
||
12 | protected $items = []; |
||
13 | |||
14 | /** |
||
15 | * Current iterator key. |
||
16 | * |
||
17 | * @var int |
||
18 | */ |
||
19 | protected $key = 0; |
||
20 | |||
21 | 6 | protected function __construct() |
|
22 | { |
||
23 | 6 | } |
|
24 | |||
25 | /** |
||
26 | * {@inheritdoc} |
||
27 | */ |
||
28 | 4 | public static function createFromArray(array $data) |
|
29 | { |
||
30 | 4 | $collection = new static(); |
|
31 | 4 | foreach ($data as $itemData) { |
|
32 | 4 | $collection->items[] = $collection->createItem($itemData); |
|
33 | } |
||
34 | |||
35 | 4 | return $collection; |
|
36 | } |
||
37 | |||
38 | /** |
||
39 | * @return array |
||
40 | */ |
||
41 | public function getItems() |
||
42 | { |
||
43 | return $this->items; |
||
44 | } |
||
45 | |||
46 | /** |
||
47 | * {@inheritdoc} |
||
48 | */ |
||
49 | 6 | public function count() |
|
50 | { |
||
51 | 6 | return count($this->items); |
|
52 | } |
||
53 | |||
54 | /** |
||
55 | * {@inheritdoc} |
||
56 | */ |
||
57 | public function key() |
||
58 | { |
||
59 | return $this->key; |
||
60 | } |
||
61 | |||
62 | /** |
||
63 | * {@inheritdoc} |
||
64 | */ |
||
65 | 2 | public function next() |
|
66 | { |
||
67 | 2 | ++$this->key; |
|
68 | 2 | } |
|
69 | |||
70 | /** |
||
71 | * @return bool |
||
72 | */ |
||
73 | public function valid() |
||
74 | { |
||
75 | return $this->key < $this->count(); |
||
76 | } |
||
77 | |||
78 | /** |
||
79 | * {@inheritdoc} |
||
80 | */ |
||
81 | 4 | public function current() |
|
82 | { |
||
83 | 4 | return $this->items[$this->key]; |
|
84 | } |
||
85 | |||
86 | /** |
||
87 | * {@inheritdoc} |
||
88 | */ |
||
89 | public function rewind() |
||
90 | { |
||
91 | $this->key = 0; |
||
92 | } |
||
93 | |||
94 | /** |
||
95 | * @param array $data |
||
96 | */ |
||
97 | abstract protected function createItem(array $data); |
||
98 | } |
||
99 |