簡體   English   中英

Symfony Finder:獲取具有特定擴展名的所有文件以及特定目錄中的所有目錄

[英]Symfony Finder: Get all the files with a specific extension and all the directories within a specific directory

我正在使用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

ABC是目錄。

當我在上面顯示的方法中將上述directory path作為$directory參數傳遞時,我得到一個包含以下元素的數組:

file1.json
file2.php
file3.php

太棒了!,但我的問題是,我怎樣才能將所有directories添加到結果數組中? 我的期望是得到一個如下所示的數組:

A
B
C
file1.json
file2.php
file3.php

在你的情況下,你和finder說話:

  • 請添加深度為0的遞歸目錄迭代器(沒關系,我們只想在root中搜索)
  • 請添加文件名迭代器(這是錯誤的,因為您只找到files )。

結果是錯誤的,因為這兩個規則相互矛盾 - 因為您只想搜索文件。

但是,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));

在這種情況下,你說:

  • 請僅在 root 中查找。
  • 請檢查 - 或歸檔或匹配我的模式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM