Skip to content

Commit 177a9b7

Browse files
committed
Merge branch 'v1.16'
* v1.16: PHPLIB-1167: Fix CachingIterator::count() on empty Cursor (#1118)
2 parents b7eb8a4 + 0d13981 commit 177a9b7

File tree

2 files changed

+51
-2
lines changed

2 files changed

+51
-2
lines changed

src/Model/CachingIterator.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,8 +110,6 @@ public function next(): void
110110
$this->iterator->next();
111111

112112
$this->storeCurrentItem();
113-
114-
$this->iteratorExhausted = ! $this->iterator->valid();
115113
}
116114

117115
next($this->items);
@@ -152,6 +150,8 @@ private function exhaustIterator(): void
152150
private function storeCurrentItem(): void
153151
{
154152
if (! $this->iterator->valid()) {
153+
$this->iteratorExhausted = true;
154+
155155
return;
156156
}
157157

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
<?php
2+
3+
namespace MongoDB\Tests\Model;
4+
5+
use MongoDB\Model\CachingIterator;
6+
use MongoDB\Tests\FunctionalTestCase;
7+
8+
class CachingIteratorFunctionalTest extends FunctionalTestCase
9+
{
10+
/** @see https://jira.mongodb.org/browse/PHPLIB-1167 */
11+
public function testEmptyCursor(): void
12+
{
13+
$collection = $this->dropCollection($this->getDatabaseName(), $this->getCollectionName());
14+
$cursor = $collection->find();
15+
$iterator = new CachingIterator($cursor);
16+
17+
$this->assertSame(0, $iterator->count());
18+
$iterator->rewind();
19+
$this->assertFalse($iterator->valid());
20+
$this->assertFalse($iterator->current());
21+
$this->assertNull($iterator->key());
22+
}
23+
24+
public function testCursor(): void
25+
{
26+
$collection = $this->dropCollection($this->getDatabaseName(), $this->getCollectionName());
27+
$collection->insertOne(['_id' => 1]);
28+
$collection->insertOne(['_id' => 2]);
29+
$cursor = $collection->find();
30+
$iterator = new CachingIterator($cursor);
31+
32+
$this->assertSame(2, $iterator->count());
33+
34+
$iterator->rewind();
35+
$this->assertTrue($iterator->valid());
36+
$this->assertNotNull($iterator->current());
37+
$this->assertSame(0, $iterator->key());
38+
39+
$iterator->next();
40+
$this->assertTrue($iterator->valid());
41+
$this->assertNotNull($iterator->current());
42+
$this->assertSame(1, $iterator->key());
43+
44+
$iterator->next();
45+
$this->assertFalse($iterator->valid());
46+
$this->assertFalse($iterator->current());
47+
$this->assertNull($iterator->key());
48+
}
49+
}

0 commit comments

Comments
 (0)