php - Symfony Finder:获取具有特定扩展名的所有文件以及特定目录中的所有目录
问题描述
我正在使用Symfony 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));
在这种情况下,你说:
- 请仅在根目录中查找。
- 请检查 - 或按我的模式归档或匹配。
推荐阅读
- python - 如何使用日期时间获取另一个国家的日期?
- angular - 我可以在 app.module 提供程序中放置一个简单的类吗?
- javascript - 在 Cypress 中上传文件
- android - 安卓 | 科特林 | 流 - 不能转换为 kotlinx.coroutines.flow.StateFlow
- reactjs - React 应用程序错误对象不支持属性或方法“最近”
- javascript - 垂直翻转问题;HTML、CSS、问题:位置/显示中的某处
- swiftui - @EnvironmentObject 不会更新 SwiftUI 中的 UI
- wordpress - Cloudinary wordpress 插件同步太慢
- android - 嵌套的 ScrollView 不显示子 recyclerview 的最后一项
- python - 需要删除每个包含特定单词的文件