Skip to content

Commit ae3dc59

Browse files
authored
PHPLIB-608 Fix wrong validity check in CachingIterator (#803)
* PHPLIB-608 Fix wrong validity check in CachingIterator * Apply review feedback
1 parent 3c6b5f2 commit ae3dc59

File tree

2 files changed

+43
-4
lines changed

2 files changed

+43
-4
lines changed

src/Model/CachingIterator.php

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -153,12 +153,10 @@ private function exhaustIterator()
153153
*/
154154
private function storeCurrentItem()
155155
{
156-
$key = $this->iterator->key();
157-
158-
if ($key === null) {
156+
if (! $this->iterator->valid()) {
159157
return;
160158
}
161159

162-
$this->items[$key] = $this->iterator->current();
160+
$this->items[$this->iterator->key()] = $this->iterator->current();
163161
}
164162
}

tests/Model/CachingIteratorTest.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace MongoDB\Tests\Model;
44

55
use Exception;
6+
use Iterator;
67
use MongoDB\Model\CachingIterator;
78
use MongoDB\Tests\TestCase;
89
use Throwable;
@@ -110,6 +111,46 @@ public function testCountWithEmptySet()
110111
$this->assertCount(0, $iterator);
111112
}
112113

114+
/**
115+
* This protects against iterators that return valid keys on invalid
116+
* positions, which was the case in ext-mongodb until PHPC-1748 was fixed.
117+
*/
118+
public function testWithWrongIterator()
119+
{
120+
$nestedIterator = new class implements Iterator {
121+
/** @var int */
122+
private $i = 0;
123+
124+
public function current()
125+
{
126+
return $this->i;
127+
}
128+
129+
public function next()
130+
{
131+
$this->i++;
132+
}
133+
134+
public function key()
135+
{
136+
return $this->i;
137+
}
138+
139+
public function valid()
140+
{
141+
return $this->i == 0;
142+
}
143+
144+
public function rewind()
145+
{
146+
$this->i = 0;
147+
}
148+
};
149+
150+
$iterator = new CachingIterator($nestedIterator);
151+
$this->assertCount(1, $iterator);
152+
}
153+
113154
private function getTraversable($items)
114155
{
115156
foreach ($items as $item) {

0 commit comments

Comments
 (0)