diff --git a/src/Model/CachingIterator.php b/src/Model/CachingIterator.php index d1ad098d4..ff0e35d55 100644 --- a/src/Model/CachingIterator.php +++ b/src/Model/CachingIterator.php @@ -110,8 +110,6 @@ public function next(): void $this->iterator->next(); $this->storeCurrentItem(); - - $this->iteratorExhausted = ! $this->iterator->valid(); } next($this->items); @@ -152,6 +150,8 @@ private function exhaustIterator(): void private function storeCurrentItem(): void { if (! $this->iterator->valid()) { + $this->iteratorExhausted = true; + return; } diff --git a/tests/Model/CachingIteratorFunctionalTest.php b/tests/Model/CachingIteratorFunctionalTest.php new file mode 100644 index 000000000..3d3ed002c --- /dev/null +++ b/tests/Model/CachingIteratorFunctionalTest.php @@ -0,0 +1,49 @@ +dropCollection($this->getDatabaseName(), $this->getCollectionName()); + $cursor = $collection->find(); + $iterator = new CachingIterator($cursor); + + $this->assertSame(0, $iterator->count()); + $iterator->rewind(); + $this->assertFalse($iterator->valid()); + $this->assertFalse($iterator->current()); + $this->assertNull($iterator->key()); + } + + public function testCursor(): void + { + $collection = $this->dropCollection($this->getDatabaseName(), $this->getCollectionName()); + $collection->insertOne(['_id' => 1]); + $collection->insertOne(['_id' => 2]); + $cursor = $collection->find(); + $iterator = new CachingIterator($cursor); + + $this->assertSame(2, $iterator->count()); + + $iterator->rewind(); + $this->assertTrue($iterator->valid()); + $this->assertNotNull($iterator->current()); + $this->assertSame(0, $iterator->key()); + + $iterator->next(); + $this->assertTrue($iterator->valid()); + $this->assertNotNull($iterator->current()); + $this->assertSame(1, $iterator->key()); + + $iterator->next(); + $this->assertFalse($iterator->valid()); + $this->assertFalse($iterator->current()); + $this->assertNull($iterator->key()); + } +}