Skip to content

PHPLIB-608 Fix wrong validity check in CachingIterator #803

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions src/Model/CachingIterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,12 +153,10 @@ private function exhaustIterator()
*/
private function storeCurrentItem()
{
$key = $this->iterator->key();

if ($key === null) {
if (! $this->iterator->valid()) {
return;
}

$this->items[$key] = $this->iterator->current();
$this->items[$this->iterator->key()] = $this->iterator->current();
}
}
41 changes: 41 additions & 0 deletions tests/Model/CachingIteratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace MongoDB\Tests\Model;

use Exception;
use Iterator;
use MongoDB\Model\CachingIterator;
use MongoDB\Tests\TestCase;
use Throwable;
Expand Down Expand Up @@ -110,6 +111,46 @@ public function testCountWithEmptySet()
$this->assertCount(0, $iterator);
}

/**
* This protects against iterators that return valid keys on invalid
* positions, which was the case in ext-mongodb until PHPC-1748 was fixed.
*/
public function testWithWrongIterator()
{
$nestedIterator = new class implements Iterator {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What a lovely use of anonymous classes!

/** @var int */
private $i = 0;

public function current()
{
return $this->i;
}

public function next()
{
$this->i++;
}

public function key()
{
return $this->i;
}

public function valid()
{
return $this->i == 0;
}

public function rewind()
{
$this->i = 0;
}
};

$iterator = new CachingIterator($nestedIterator);
$this->assertCount(1, $iterator);
}

private function getTraversable($items)
{
foreach ($items as $item) {
Expand Down