Skip to content

Support counting non-Iterator Traversable objects #2642

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 1 commit into from
May 22, 2017
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
5 changes: 5 additions & 0 deletions src/Framework/Constraint/Count.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
namespace PHPUnit\Framework\Constraint;

use Countable;
use Iterator;
use IteratorAggregate;
use Traversable;
use Generator;
Expand Down Expand Up @@ -65,6 +66,10 @@ protected function getCountOf($other)
return $this->getCountOfGenerator($iterator);
}

if (!$iterator instanceof Iterator) {
return \iterator_count($iterator);
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Previously, this PR used a ternary when assigning $key. This guard conditional is likely clearer and avoids making an assumption about how a null value of $key will be handled later in the code (i.e. deciding whether to attempt rewinding the iterator).


$key = $iterator->key();
$count = \iterator_count($iterator);

Expand Down
15 changes: 15 additions & 0 deletions tests/Framework/Constraint/CountTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,19 @@ public function testCountGeneratorsDoNotRewind()
$countConstraint->evaluate($generator, '', true);
$this->assertEquals(null, $generator->current());
}

public function testCountTraversable()
{
$countConstraint = new Count(5);

// DatePeriod is used as an object that is Traversable but does not
// implement Iterator or IteratorAggregate. The following ISO 8601
// recurring time interval will yield five total DateTime objects.
$datePeriod = new \DatePeriod('R4/2017-05-01T00:00:00Z/P1D');

$this->assertInstanceOf(\Traversable::class, $datePeriod);
$this->assertNotInstanceOf(\Iterator::class, $datePeriod);
$this->assertNotInstanceOf(\IteratorAggregate::class, $datePeriod);
$this->assertTrue($countConstraint->evaluate($datePeriod, '', true));
}
}