Skip to content

Commit

Permalink
Fix wrong behavior of hasNext()
Browse files Browse the repository at this point in the history
Fixes #91.
  • Loading branch information
alcaeus committed Apr 8, 2016
1 parent 985ec39 commit 0b27c0e
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG-1.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ milestone.

* [#90](https://github.com/alcaeus/mongo-php-adapter/pull/90) ensures that database
and collection names are properly cast to string on creation.
* [#94](https://github.com/alcaeus/mongo-php-adapter/pull/94) fixes an error in
`MongoCursor::hasNext` that led to wrong data being returned.

1.0.1 (2016-04-01)
------------------
Expand Down
2 changes: 1 addition & 1 deletion lib/Alcaeus/MongoDbAdapter/AbstractCursor.php
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ public function __sleep()
* This is necessary because hasNext() might advance the iterator but we still
* need to be able to return the current object.
*/
private function storeIteratorState()
protected function storeIteratorState()
{
if (! $this->startedIterating) {
$this->current = null;
Expand Down
7 changes: 6 additions & 1 deletion lib/Mongo/MongoCursor.php
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,12 @@ public function getNext()
*/
public function hasNext()
{
if ($this->cursorNeedsAdvancing) {
if (! $this->startedIterating) {
$this->ensureIterator();
$this->startedIterating = true;
$this->storeIteratorState();
$this->cursorNeedsAdvancing = false;
} elseif ($this->cursorNeedsAdvancing) {
$this->ensureIterator()->next();
$this->cursorNeedsAdvancing = false;
}
Expand Down
22 changes: 22 additions & 0 deletions tests/Alcaeus/MongoDbAdapter/Mongo/MongoCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1488,6 +1488,28 @@ public function testSelectCollectionWithDatabaseObject()
$collection = $client->selectCollection($database, 'test');
$this->assertSame('mongo-php-adapter.test', (string) $collection);
}

public function testHasNextLoop()
{
$collection = $this->getCollection();
for ($i = 0; $i < 5; $i++) {
$document = ['i' => $i];
$collection->insert($document);
}

$cursor = $collection->find()->sort(['i' => 1]);
$data = [];
$i = 0;
while ($cursor->hasNext()) {
$this->assertSame($i < 5, $cursor->hasNext());
$row = $cursor->getNext();
$this->assertSame($i, $row['i']);
$data[] = $row;
$i++;
}

$this->assertCount(5, $data);
}
}

class PrivatePropertiesStub
Expand Down

0 comments on commit 0b27c0e

Please sign in to comment.