Skip to content
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

Preserve iterator position when counting #2570

Merged
merged 1 commit into from
Nov 3, 2023
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
2 changes: 2 additions & 0 deletions lib/Doctrine/ODM/MongoDB/Iterator/CachingIterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,9 @@ public function __construct(Traversable $iterator)
/** @see https://php.net/countable.count */
public function count(): int
{
$currentKey = key($this->items);
$this->exhaustIterator();
for (reset($this->items); key($this->items) !== $currentKey; next($this->items));

return count($this->items);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,26 +114,32 @@ public function testToArrayAfterPartialIteration(): void
public function testCount(): void
{
$iterator = new CachingIterator($this->getTraversable([1, 2, 3]));
$this->assertCount(3, $iterator);
self::assertCount(3, $iterator);
}

public function testCountAfterPartialIteration(): void
{
$iterator = new CachingIterator($this->getTraversable([1, 2, 3]));

$iterator->rewind();
$this->assertTrue($iterator->valid());
$this->assertSame(0, $iterator->key());
$this->assertSame(1, $iterator->current());
self::assertTrue($iterator->valid());
self::assertSame(0, $iterator->key());
self::assertSame(1, $iterator->current());

$iterator->next();
$this->assertCount(3, $iterator);
self::assertSame(1, $iterator->key());
self::assertSame(2, $iterator->current());

self::assertCount(3, $iterator);
self::assertTrue($iterator->valid());
self::assertSame(1, $iterator->key());
self::assertSame(2, $iterator->current());
}

public function testCountWithEmptySet(): void
{
$iterator = new CachingIterator($this->getTraversable([]));
$this->assertCount(0, $iterator);
self::assertCount(0, $iterator);
}

/**
Expand Down Expand Up @@ -172,7 +178,7 @@ public function rewind(): void
};

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

/**
Expand Down