4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Finder\Iterator;
15 * ExcludeDirectoryFilterIterator filters out directories.
17 * @author Fabien Potencier <fabien@symfony.com>
19 class ExcludeDirectoryFilterIterator extends FilterIterator implements \RecursiveIterator
23 private $excludedDirs = array();
24 private $excludedPattern;
29 * @param \Iterator $iterator The Iterator to filter
30 * @param array $directories An array of directories to exclude
32 public function __construct(\Iterator $iterator, array $directories)
34 $this->iterator = $iterator;
35 $this->isRecursive = $iterator instanceof \RecursiveIterator;
37 foreach ($directories as $directory) {
38 $directory = rtrim($directory, '/');
39 if (!$this->isRecursive || false !== strpos($directory, '/')) {
40 $patterns[] = preg_quote($directory, '#');
42 $this->excludedDirs[$directory] = true;
46 $this->excludedPattern = '#(?:^|/)(?:'.implode('|', $patterns).')(?:/|$)#';
49 parent::__construct($iterator);
53 * Filters the iterator values.
55 * @return bool True if the value should be kept, false otherwise
57 public function accept()
59 if ($this->isRecursive && isset($this->excludedDirs[$this->getFilename()]) && $this->isDir()) {
63 if ($this->excludedPattern) {
64 $path = $this->isDir() ? $this->current()->getRelativePathname() : $this->current()->getRelativePath();
65 $path = str_replace('\\', '/', $path);
67 return !preg_match($this->excludedPattern, $path);
73 public function hasChildren()
75 return $this->isRecursive && $this->iterator->hasChildren();
78 public function getChildren()
80 $children = new self($this->iterator->getChildren(), array());
81 $children->excludedDirs = $this->excludedDirs;
82 $children->excludedPattern = $this->excludedPattern;