Skip to content

Commit

Permalink
[Finder] added Finder::append() method to be able to combine several …
Browse files Browse the repository at this point in the history
…Finder instances into one
  • Loading branch information
fabpot committed Mar 25, 2011
1 parent 2d27b13 commit 8d84fdf
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
31 changes: 30 additions & 1 deletion src/Symfony/Component/Finder/Finder.php
Expand Up @@ -41,6 +41,7 @@ class Finder implements \IteratorAggregate
private $ignoreVCS = true;
private $dirs = array();
private $dates = array();
private $iterators = array();

/**
* Restricts the matching to directories only.
Expand Down Expand Up @@ -356,7 +357,7 @@ public function getIterator()
throw new \LogicException('You must call the in() method before iterating over a Finder.');
}

if (1 === count($this->dirs)) {
if (1 === count($this->dirs) && 0 === count($this->iterators)) {
return $this->searchInDirectory($this->dirs[0]);
}

Expand All @@ -365,9 +366,37 @@ public function getIterator()
$iterator->append($this->searchInDirectory($dir));
}

foreach ($this->iterators as $it) {
$iterator->append($it);
}

return $iterator;
}

/**
* Appends an existing set of files/directories to the finder.
*
* The set can be another Finder, an Iterator, an IteratorAggregate, or even a plain array.
*
* @param mixed $iterator
*/
public function append($iterator)
{
if ($iterator instanceof \IteratorAggregate) {
$this->iterators[] = $iterator->getIterator();
} elseif ($iterator instanceof \Iterator) {
$this->iterators[] = $iterator;
} elseif ($iterator instanceof \Traversable || is_array($iterator)) {
$it = new \ArrayIterator();
foreach ($iterator as $file) {
$it->append($file instanceof \SplFileInfo ? $file : new \SplFileInfo($file));
}
$this->iterators[] = $it;
} else {
throw new \InvalidArgumentException('Finder::append() method wrong argument type.');
}
}

private function searchInDirectory($dir)
{
$flags = \RecursiveDirectoryIterator::SKIP_DOTS;
Expand Down
23 changes: 23 additions & 0 deletions tests/Symfony/Tests/Component/Finder/FinderTest.php
Expand Up @@ -262,6 +262,29 @@ public function testRelativePathname()
$this->assertEquals($paths, $ref);
}

public function testAppendWithAFinder()
{
$finder = new Finder();
$finder->files()->in(self::$tmpDir.'/foo');

$finder1 = new Finder();
$finder1->directories()->in(self::$tmpDir);

$finder->append($finder1);

$this->assertIterator($this->toAbsolute(array('foo', 'foo/bar.tmp', 'toto')), $finder->getIterator());
}

public function testAppendWithAnArray()
{
$finder = new Finder();
$finder->files()->in(self::$tmpDir.'/foo');

$finder->append($this->toAbsolute(array('foo', 'toto')));

$this->assertIterator($this->toAbsolute(array('foo', 'foo/bar.tmp', 'toto')), $finder->getIterator());
}

protected function toAbsolute($files)
{
$f = array();
Expand Down

0 comments on commit 8d84fdf

Please sign in to comment.