Skip to content

Commit

Permalink
Support counting non-Iterator Traversable objects
Browse files Browse the repository at this point in the history
Extension classes may implement Traversable without also implementing Iterator or IteratorAggregate.
  • Loading branch information
jmikola committed May 22, 2017
1 parent 104a9bd commit e9277ff
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
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);
}

$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));
}
}

0 comments on commit e9277ff

Please sign in to comment.