Commit | Line | Data |
---|---|---|
7f254ad8 AE |
1 | <?php |
2 | ||
3 | /* | |
4 | * This file is part of the Symfony package. | |
5 | * | |
6 | * (c) Fabien Potencier <fabien@symfony.com> | |
7 | * | |
8 | * For the full copyright and license information, please view the LICENSE | |
9 | * file that was distributed with this source code. | |
10 | */ | |
11 | ||
12 | namespace Symfony\Component\Finder\Iterator; | |
13 | ||
14 | /** | |
15 | * ExcludeDirectoryFilterIterator filters out directories. | |
16 | * | |
17 | * @author Fabien Potencier <fabien@symfony.com> | |
18 | */ | |
19 | class ExcludeDirectoryFilterIterator extends FilterIterator implements \RecursiveIterator | |
20 | { | |
21 | private $iterator; | |
22 | private $isRecursive; | |
23 | private $excludedDirs = array(); | |
24 | private $excludedPattern; | |
25 | ||
26 | /** | |
27 | * Constructor. | |
28 | * | |
29 | * @param \Iterator $iterator The Iterator to filter | |
30 | * @param array $directories An array of directories to exclude | |
31 | */ | |
32 | public function __construct(\Iterator $iterator, array $directories) | |
33 | { | |
34 | $this->iterator = $iterator; | |
35 | $this->isRecursive = $iterator instanceof \RecursiveIterator; | |
36 | $patterns = array(); | |
37 | foreach ($directories as $directory) { | |
38 | if (!$this->isRecursive || false !== strpos($directory, '/')) { | |
39 | $patterns[] = preg_quote($directory, '#'); | |
40 | } else { | |
41 | $this->excludedDirs[$directory] = true; | |
42 | } | |
43 | } | |
44 | if ($patterns) { | |
45 | $this->excludedPattern = '#(?:^|/)(?:'.implode('|', $patterns).')(?:/|$)#'; | |
46 | } | |
47 | ||
48 | parent::__construct($iterator); | |
49 | } | |
50 | ||
51 | /** | |
52 | * Filters the iterator values. | |
53 | * | |
54 | * @return bool true if the value should be kept, false otherwise | |
55 | */ | |
56 | public function accept() | |
57 | { | |
58 | if ($this->isRecursive && isset($this->excludedDirs[$this->getFilename()]) && $this->isDir()) { | |
59 | return false; | |
60 | } | |
61 | ||
62 | if ($this->excludedPattern) { | |
63 | $path = $this->isDir() ? $this->current()->getRelativePathname() : $this->current()->getRelativePath(); | |
64 | $path = str_replace('\\', '/', $path); | |
65 | ||
66 | return !preg_match($this->excludedPattern, $path); | |
67 | } | |
68 | ||
69 | return true; | |
70 | } | |
71 | ||
72 | public function hasChildren() | |
73 | { | |
74 | return $this->isRecursive && $this->iterator->hasChildren(); | |
75 | } | |
76 | ||
77 | public function getChildren() | |
78 | { | |
79 | $children = new self($this->iterator->getChildren(), array()); | |
80 | $children->excludedDirs = $this->excludedDirs; | |
81 | $children->excludedPattern = $this->excludedPattern; | |
82 | ||
83 | return $children; | |
84 | } | |
85 | } |