我可以让递归目录迭代器跳过不可读的目录吗?

2022-08-31 00:38:21
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator(".")) as $file) {
  echo "$file\n";
}

有没有办法让这段代码在我尝试列出的目录内有一个不可读的子目录时,抛出 UnexpectedValueException“未能打开dir:权限被拒绝”?

更新

转换为并显式调用包装在中没有帮助。此代码:foreach()while()Iterator::next()try() catch {}

$iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("."));
while($iter->valid()) {
    $file = $iter->current();
    echo "$file\n";
    try {
        $iter->next();
    } catch(UnexpectedValueException $e) {
    }
};

是无限循环,如果存在不可读的子目录。


答案 1

显然,您可以将参数传递给构造函数。文档中只有一个标志,但它完全符合您的要求:.$flagscatches exceptions during getChildren() calls and simply jumps to the next element

将课程创建代码更改为

new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator("."), 
    RecursiveIteratorIterator::LEAVES_ONLY,
    RecursiveIteratorIterator::CATCH_GET_CHILD);

它应该工作


答案 2

你可以做这样的事情:

class ReadableFilter extends RecursiveFilterIterator{
    public function accept(){
            return $this->current()->isReadable();
    }
}

$filteredIterator = new RecursiveIteratorIterator(new ReadableFilter(new RecursiveDirectoryIterator(".")));

foreach ($filteredIterator as $file){
    echo "$file\n";
}

推荐