diff --git a/src/Symfony/Component/Finder/Finder.php b/src/Symfony/Component/Finder/Finder.php index f09df80a85..0f5dd17f36 100644 --- a/src/Symfony/Component/Finder/Finder.php +++ b/src/Symfony/Component/Finder/Finder.php @@ -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) { diff --git a/src/Symfony/Component/Finder/Tests/FinderTest.php b/src/Symfony/Component/Finder/Tests/FinderTest.php index ca58f1894b..fe29424bb2 100644 --- a/src/Symfony/Component/Finder/Tests/FinderTest.php +++ b/src/Symfony/Component/Finder/Tests/FinderTest.php @@ -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) {