The standard way to recursively scan directories via SPL iterators is:
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $file) {
print $file->getPathname() . PHP_EOL;
}
I want a composable set of filters to apply to my recursive file search. I'm using a RecursiveDirectoryIterator to scan a directory structure.
I want to apply more than one filter to my directory structure.
My set up code:
$filters = new FilterRuleset(
new RecursiveDirectoryIterator($path)
);
$filters->addFilter(new FilterLapsedDirs);
$filters->addFilter(new IncludeExtension('wav'));
$files = new RecursiveIteratorIterator(
$filters, RecursiveIteratorIterator::CHILD_FIRST
);
I thought I could apply N filters by using rule set:
class FilterRuleset extends RecursiveFilterIterator {
private $filters = array();
public function addFilter($filter) {
$this->filters[] = $filter;
}
public function accept() {
$file = $this->current();
foreach ($this->filters as $filter) {
if (!$filter->accept($file)) {
return false;
}
}
return true;
}
}
The filtering I set up is not working as intended. When I check the filters in FilterRuleset they are populated on the first call, then blank on subsequent calls. Its as if internally RecursiveIteratorIterator is re-instantiating my FilterRuleset.
public function accept() {
print_r($this->filters);
$file = $this->current();
foreach ($this->filters as $filter) {
if (!$filter->accept($file)) {
return false;
}
}
return true;
}
Output:
Array
(
[0] => FilterLapsedDirs Object
(
)
[1] => IncludeExtension Object
(
[ext:private] => wav
)
)
Array
(
)
Array
(
)
Array
(
)
Array
(
)
Array
(
)
Array
(
)
I'm using PHP 5.1.6 but have tested it on 5.4.14 and there's no difference. Any ideas?