18
18
*/
19
19
class ExcludeDirectoryFilterIterator extends FilterIterator implements \RecursiveIterator
20
20
{
21
+ private $ iterator ;
21
22
private $ isRecursive ;
22
- private $ patterns = array ();
23
+ private $ excludedDirs = array ();
24
+ private $ excludedPattern ;
23
25
24
26
/**
25
27
* Constructor.
@@ -29,9 +31,18 @@ class ExcludeDirectoryFilterIterator extends FilterIterator implements \Recursiv
29
31
*/
30
32
public function __construct (\Iterator $ iterator , array $ directories )
31
33
{
34
+ $ this ->iterator = $ iterator ;
32
35
$ this ->isRecursive = $ iterator instanceof \RecursiveIterator;
36
+ $ patterns = array ();
33
37
foreach ($ directories as $ directory ) {
34
- $ this ->patterns [] = '#(^|/) ' .preg_quote ($ 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 ).')(?:/|$)# ' ;
35
46
}
36
47
37
48
parent ::__construct ($ iterator );
@@ -44,26 +55,30 @@ public function __construct(\Iterator $iterator, array $directories)
44
55
*/
45
56
public function accept ()
46
57
{
47
- $ path = $ this ->isDir () ? $ this ->current ()->getRelativePathname () : $ this ->current ()->getRelativePath ();
48
- $ path = str_replace ('\\' , '/ ' , $ path );
49
- foreach ($ this ->patterns as $ pattern ) {
50
- if (preg_match ($ pattern , $ path )) {
51
- return false ;
52
- }
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 );
53
67
}
54
68
55
69
return true ;
56
70
}
57
71
58
72
public function hasChildren ()
59
73
{
60
- return $ this ->isRecursive && $ this ->getInnerIterator () ->hasChildren ();
74
+ return $ this ->isRecursive && $ this ->iterator ->hasChildren ();
61
75
}
62
76
63
77
public function getChildren ()
64
78
{
65
- $ children = new self ($ this ->getInnerIterator ()->getChildren (), array ());
66
- $ children ->patterns = $ this ->patterns ;
79
+ $ children = new self ($ this ->iterator ->getChildren (), array ());
80
+ $ children ->excludedDirs = $ this ->excludedDirs ;
81
+ $ children ->excludedPattern = $ this ->excludedPattern ;
67
82
68
83
return $ children ;
69
84
}
0 commit comments