Skip to content

Commit e847b06

Browse files
committed
PHPLIB-327: ChangeStream::next() should not increment key for the first event
1 parent d42c3b4 commit e847b06

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

src/ChangeStream.php

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,8 @@ class ChangeStream implements Iterator
3838
private $resumeToken;
3939
private $resumeCallable;
4040
private $csIt;
41-
private $key;
41+
private $key = 0;
42+
private $hasAdvanced = false;
4243

4344
const CURSOR_NOT_FOUND = 43;
4445

@@ -53,8 +54,6 @@ public function __construct(Cursor $cursor, callable $resumeCallable)
5354
{
5455
$this->resumeCallable = $resumeCallable;
5556
$this->csIt = new IteratorIterator($cursor);
56-
57-
$this->key = 0;
5857
}
5958

6059
/**
@@ -97,7 +96,10 @@ public function next()
9796
$this->csIt->next();
9897
if ($this->valid()) {
9998
$this->resumeToken = $this->extractResumeToken($this->csIt->current());
100-
$this->key++;
99+
if ($this->hasAdvanced) {
100+
$this->key++;
101+
}
102+
$this->hasAdvanced = true;
101103
}
102104
} catch (RuntimeException $e) {
103105
if (strpos($e->getMessage(), "not master") !== false) {
@@ -126,6 +128,7 @@ public function rewind()
126128
$this->csIt->rewind();
127129
if ($this->valid()) {
128130
$this->resumeToken = $this->extractResumeToken($this->csIt->current());
131+
$this->hasAdvanced = true;
129132
}
130133
} catch (RuntimeException $e) {
131134
if (strpos($e->getMessage(), "not master") !== false) {

tests/Operation/WatchFunctionalTest.php

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
namespace MongoDB\Tests\Operation;
44

55
use MongoDB\ChangeStream;
6-
use MongoDB\Client;
76
use MongoDB\Driver\Manager;
87
use MongoDB\Driver\ReadPreference;
98
use MongoDB\Driver\Server;
@@ -536,6 +535,23 @@ public function provideTypeMapOptionsAndExpectedChangeDocument()
536535
];
537536
}
538537

538+
public function testNextAdvancesKey()
539+
{
540+
$operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
541+
$changeStream = $operation->execute($this->getPrimaryServer());
542+
543+
$this->insertDocument(['x' => 1]);
544+
$this->insertDocument(['x' => 2]);
545+
546+
$changeStream->next();
547+
548+
$this->assertSame(0, $changeStream->key());
549+
550+
$changeStream->next();
551+
552+
$this->assertSame(1, $changeStream->key());
553+
}
554+
539555
private function insertDocument($document)
540556
{
541557
$insertOne = new InsertOne($this->getDatabaseName(), $this->getCollectionName(), $document);

0 commit comments

Comments
 (0)