Skip to content

Commit b07cc9d

Browse files
committed
PHPLIB-608 Fix wrong validity check in CachingIterator
1 parent 3c6b5f2 commit b07cc9d

File tree

2 files changed

+43
-3
lines changed

2 files changed

+43
-3
lines changed

src/Model/CachingIterator.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -153,12 +153,12 @@ 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

160+
$key = $this->iterator->key();
161+
162162
$this->items[$key] = $this->iterator->current();
163163
}
164164
}

tests/Model/CachingIteratorTest.php

Lines changed: 40 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,45 @@ 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+
private $i = 0;
122+
123+
public function current()
124+
{
125+
return $this->i;
126+
}
127+
128+
public function next()
129+
{
130+
$this->i++;
131+
}
132+
133+
public function key()
134+
{
135+
return $this->i;
136+
}
137+
138+
public function valid()
139+
{
140+
return $this->i == 0;
141+
}
142+
143+
public function rewind()
144+
{
145+
$this->i = 0;
146+
}
147+
};
148+
149+
$iterator = new CachingIterator($nestedIterator);
150+
$this->assertCount(1, $iterator);
151+
}
152+
113153
private function getTraversable($items)
114154
{
115155
foreach ($items as $item) {

0 commit comments

Comments
 (0)