问题描述
我正在使用Symphony Finder
来获取具有特定扩展名的所有文件以及特定目录中的所有目录。
protected function getDirectoryContent(string $directory): array
{
$finder = Finder::create()
->in($directory)
->depth(0)
->name(['*.json','*.PHP'])
->sortByName();
return iterator_to_array($finder,true);
}
通过这种方式,此方法仅返回特定目录中所有扩展名为.PHP
或.json
的文件。例如,我要查找的目录结构如下:
/my/directory/
├── A
├── A.JSON
├── anotherfile.kas
├── file0.ds
├── file1.json
├── file2.PHP
├── file3.PHP
├── B
└── C
A
,B
和C
是目录。
当我在上面显示的方法中将上面的directory path
作为参数$directory
传递时,我得到一个包含以下元素的数组:
file1.json
file2.PHP
file3.PHP
太好了!但是我的问题是,如何将所有directories
添加到结果数组中?我的期望是得到一个如下数组:
A
B
C
file1.json
file2.PHP
file3.PHP
解决方法
在这种情况下,您与finder对话:
- 请添加深度为0的递归目录迭代器(可以,我们只想在根目录中搜索)
- 请添加文件名迭代器(这是错误的,因为您只能找到文件)。
结果是错误的,因为这两个规则相互矛盾-因为您只想搜索文件。
但是,symfony finder可以将CallbackIterator
与过滤器模型一起使用。在这种情况下,您可以添加许多规则或条件。在您的示例中:
namespace Acme;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
include __DIR__.'/vendor/autoload.php';
$finder = Finder::create();
$finder
->in(__DIR__)
->depth(0)
->filter(static function (SplFileInfo $file) {
return $file->isDir() || \preg_match('/\.(php|json)$/',$file->getPathname());
});
print_r(\iterator_to_array($finder));
在这种情况下,您说:
- 请仅在根目录中查找。
- 请检查-或根据我的模式进行归档或匹配。