Skip to content

Commit

Permalink
PHPLIB-1167: Fix CachingIterator::count() on empty Cursor (#1118)
Browse files Browse the repository at this point in the history
Fix error: "Cannot advance a completed or failed cursor."
  • Loading branch information
GromNaN committed Jun 26, 2023
1 parent d4cdf05 commit 0d13981
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Model/CachingIterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,6 @@ public function next(): void
$this->iterator->next();

$this->storeCurrentItem();

$this->iteratorExhausted = ! $this->iterator->valid();
}

next($this->items);
Expand Down Expand Up @@ -152,6 +150,8 @@ private function exhaustIterator(): void
private function storeCurrentItem(): void
{
if (! $this->iterator->valid()) {
$this->iteratorExhausted = true;

return;
}

Expand Down
49 changes: 49 additions & 0 deletions tests/Model/CachingIteratorFunctionalTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace MongoDB\Tests\Model;

use MongoDB\Model\CachingIterator;
use MongoDB\Tests\FunctionalTestCase;

class CachingIteratorFunctionalTest extends FunctionalTestCase
{
/** @see https://jira.mongodb.org/browse/PHPLIB-1167 */
public function testEmptyCursor(): void
{
$collection = $this->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());
}
}

0 comments on commit 0d13981

Please sign in to comment.