File tree 2 files changed +45
-4
lines changed
2 files changed +45
-4
lines changed Original file line number Diff line number Diff line change 25
25
26
26
use function count ;
27
27
use function current ;
28
- use function key ;
29
28
use function next ;
30
29
use function reset ;
31
30
40
39
*/
41
40
class CachingIterator implements Countable, Iterator
42
41
{
42
+ private const FIELD_KEY = 0 ;
43
+ private const FIELD_VALUE = 1 ;
44
+
43
45
/** @var array */
44
46
private $ items = [];
45
47
@@ -87,7 +89,9 @@ public function count()
87
89
#[ReturnTypeWillChange]
88
90
public function current ()
89
91
{
90
- return current ($ this ->items );
92
+ $ currentItem = current ($ this ->items );
93
+
94
+ return $ currentItem !== false ? $ currentItem [self ::FIELD_VALUE ] : false ;
91
95
}
92
96
93
97
/**
@@ -97,7 +101,9 @@ public function current()
97
101
#[ReturnTypeWillChange]
98
102
public function key ()
99
103
{
100
- return key ($ this ->items );
104
+ $ currentItem = current ($ this ->items );
105
+
106
+ return $ currentItem !== false ? $ currentItem [self ::FIELD_KEY ] : null ;
101
107
}
102
108
103
109
/**
@@ -165,6 +171,10 @@ private function storeCurrentItem()
165
171
return ;
166
172
}
167
173
168
- $ this ->items [$ this ->iterator ->key ()] = $ this ->iterator ->current ();
174
+ // Storing a new item in the internal cache
175
+ $ this ->items [] = [
176
+ self ::FIELD_KEY => $ this ->iterator ->key (),
177
+ self ::FIELD_VALUE => $ this ->iterator ->current (),
178
+ ];
169
179
}
170
180
}
Original file line number Diff line number Diff line change @@ -152,6 +152,26 @@ public function rewind(): void
152
152
$ this ->assertCount (1 , $ iterator );
153
153
}
154
154
155
+ public function testCountNonUniqueKeys (): void
156
+ {
157
+ $ iterator = new CachingIterator ($ this ->getNonUniqueTraversable ([1 , 2 , 3 ]));
158
+ $ this ->assertCount (3 , $ iterator );
159
+ }
160
+
161
+ public function testIterationNonUniqueKeys (): void
162
+ {
163
+ $ iterator = new CachingIterator ($ this ->getNonUniqueTraversable ([1 , 2 , 3 ]));
164
+
165
+ $ expectedItem = 1 ;
166
+
167
+ foreach ($ iterator as $ key => $ item ) {
168
+ $ this ->assertSame (0 , $ key );
169
+ $ this ->assertSame ($ expectedItem ++, $ item );
170
+ }
171
+
172
+ $ this ->assertFalse ($ iterator ->valid ());
173
+ }
174
+
155
175
private function getTraversable ($ items )
156
176
{
157
177
foreach ($ items as $ item ) {
@@ -162,4 +182,15 @@ private function getTraversable($items)
162
182
}
163
183
}
164
184
}
185
+
186
+ private function getNonUniqueTraversable ($ items )
187
+ {
188
+ foreach ($ items as $ item ) {
189
+ if ($ item instanceof Exception) {
190
+ throw $ item ;
191
+ } else {
192
+ yield 0 => $ item ;
193
+ }
194
+ }
195
+ }
165
196
}
You can’t perform that action at this time.
0 commit comments