From 53b7810cf93cbe457cd48e25ff839a96f455123c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Thu, 22 Jun 2023 19:59:50 +0200 Subject: [PATCH] PHPLIB-1167: Fix CachingIterator::count on empty Cursor Fix error: Cannot advance a completed or failed cursor. --- src/Model/CachingIterator.php | 4 +- tests/Model/CachingIteratorFunctionalTest.php | 49 +++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 tests/Model/CachingIteratorFunctionalTest.php 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()); + } +}