/** * Constructs the iterator * @param string $path The folder path * @param int $depth The depth to recourse * @param callable[] $filters An array of filters used to restrict the resulting list of files or folders */ public function __construct($path, $depth = null, array $filters = array()) { //TODO: verify path exists and filters are callable $this->path = (string) $path; //create the iterator $flags = \FilesystemIterator::SKIP_DOTS; if ($depth === 0) { $this->iterator = new \EmptyIterator(); } else { if ($depth === 1) { $this->iterator = new \FilesystemIterator($path, $flags); } else { $this->iterator = new \RecursiveDirectoryIterator($path, $flags); $this->iterator = new \RecursiveIteratorIterator($this->iterator, \RecursiveIteratorIterator::SELF_FIRST); if ($depth) { $this->iterator->setMaxDepth($depth - 1); } } } //decorate iterator with filters if (count($filters)) { $this->iterator = new \CallbackFilterIterator($this->iterator, function ($path) use($filters) { foreach ($filters as $filter) { if (!$filter($path)) { return false; } } return true; }); } }