Implement Countable

This commit is contained in:
Manuel de Ruiter 2012-04-22 16:13:31 +02:00
parent 5690430587
commit 6154ae5b28
2 changed files with 50 additions and 1 deletions

View File

@ -26,7 +26,7 @@ namespace Symfony\Component\Finder;
*
* @api
*/
class Finder implements \IteratorAggregate
class Finder implements \IteratorAggregate, \Countable
{
const IGNORE_VCS_FILES = 1;
const IGNORE_DOT_FILES = 2;
@ -558,6 +558,16 @@ class Finder implements \IteratorAggregate
throw new \InvalidArgumentException('Finder::append() method wrong argument type.');
}
}
/**
* Counts all the results collected by the iterators.
*
* @return int
*/
public function count()
{
return iterator_count($this->getIterator());
}
private function searchInDirectory($dir)
{

View File

@ -320,6 +320,45 @@ class FinderTest extends Iterator\RealIteratorTestCase
$this->assertIterator($this->toAbsolute(array('foo', 'foo/bar.tmp', 'toto')), $finder->getIterator());
}
public function testCountDirectories()
{
$finder = new Finder();
$directory = $finder->directories()->in(self::$tmpDir);
$i = 0;
foreach ($directory as $dir) {
$i++;
}
$this->assertCount($i, $directory);
}
public function testCountFiles()
{
$finder = new Finder();
$files = $finder->files()->in(__DIR__.DIRECTORY_SEPARATOR.'Fixtures');
$i = 0;
foreach ($files as $file) {
$i++;
}
$this->assertCount($i, $files);
}
public function testCountWithoutIn()
{
$finder = new Finder();
$finder->files();
try {
count($finder);
$this->fail('Countable makes use of the getIterator command');
} catch (\Exception $e) {
$this->assertInstanceOf('LogicException', $e, '->getIterator() throws \LogicException when no logic has been entered');
}
}
protected function toAbsolute($files)
{