Symfony Finder:获取具有特定扩展名的所有文件以及特定目录中的所有目录

leo*_*sta 3 php symfony symfony4

我正在使用 来Symfony Finder获取具有特定扩展名的所有文件以及特定目录中的所有目录。

\n
\n    protected function getDirectoryContent(string $directory): array\n    {\n        $finder = Finder::create()\n            ->in($directory)\n            ->depth(0)\n            ->name(['*.json', '*.php'])\n            ->sortByName();\n\n        return iterator_to_array($finder, true);\n    }\n\n
Run Code Online (Sandbox Code Playgroud)\n

这样,该方法只返回所有具有扩展名.php.json在某个目录内的文件。例如,我正在查看的目录结构如下:

\n
/my/directory/\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 A\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 A.JSON\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 anotherfile.kas\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 file0.ds\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 file1.json\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 file2.php\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 file3.php\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 B\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 C\n
Run Code Online (Sandbox Code Playgroud)\n

ABC是目录。

\n

当我将上面的内容directory path作为$directory参数传递到上面所示的方法中时,我得到一个包含以下元素的数组:

\n
file1.json\nfile2.php\nfile3.php\n
Run Code Online (Sandbox Code Playgroud)\n

太棒了!但我的问题是,我怎样才能将所有这些添加directories到结果数组中?我的期望是得到一个如下所示的数组:

\n
A\nB\nC\nfile1.json\nfile2.php\nfile3.php\n
Run Code Online (Sandbox Code Playgroud)\n

Zhu*_*ukV 11

在您的情况下,您与查找者交谈:

  • 请添加深度为 0 的递归目录迭代器(没关系,我们只想在根目录中搜索)
  • 请添加文件名迭代器(这是错误的,因为您只找到files)。

结果是错误的,因为这两个规则相互矛盾 - 因为你只想搜索文件。

CallbackIterator但是,symfony finder 可以与过滤器模型一起使用。在这种情况下,您可以添加许多规则或条件。在你的例子中:

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));
Run Code Online (Sandbox Code Playgroud)

在这种情况下,你说:

  • 请仅在根目录中查找。
  • 请检查 - 或归档或按照我的模式进行匹配。