【问题标题】:Exclude directories by missing file with Symfony Finder使用 Symfony Finder 通过丢失文件排除目录
【发布时间】:2018-05-10 10:30:51
【问题描述】:

有没有办法排除缺少某些文件的文件夹?

例如我有这样的文件夹:

FolderA
    aaa.php
    bbb.php
    ccc.php

FolderB
    aaa.php
    bbb.php
    ccc.php

FolderC
    aaa.php

FolderD
    aaa.php
    bbb.php
    ccc.php

我只想拥有FolderAFolderBFolderD(或排除FolderC),因为FolderC 没有所有预期的文件。

当前来源

$dirs   = [];
$finder = new Finder();
$finder->directories()->in(__DIR__)->depth('== 0');
foreach ($finder as $directory){
        $dirs [] = $directory->getRelativePathname();
}
print_r($dirs);

电流输出:

array(
    [0] => FolderA
    [1] => FolderB
    [2] => FolderC
    [3] => FolderD
)

【问题讨论】:

    标签: php symfony finder symfony-finder


    【解决方案1】:

    一种天真的方法:

    <?php
    
    require_once(__DIR__.'/vendor/autoload.php');
    
    use Symfony\Component\Finder\Finder;
    
    $dirs   = [];
    $finder = new Finder();
    $finder->directories()->in(__DIR__)->depth('== 0');
    
    $requiredFiles = ['aaa.php', 'bbb.php', 'ccc.php'];
    
    foreach ($finder as $directory) {
        $fullPath = $directory->getPathname();
    
        // if one file is not in this directory, ignore this directory
        foreach ($requiredFiles as $requiredFile) {
            if (!file_exists($fullPath.'/'.$requiredFile)) {
                continue 2;
            }
        }
    
        $dirs[] = $directory->getRelativePathname();
    }
    
    print_r($dirs);
    

    它会输出这个:

    Array
    (
        [0] => FolderD
        [1] => FolderB
        [2] => FolderA
    )
    

    如果您想要对文件夹进行排序,只需在 foreach 块之后调用 sort($dirs);

    【讨论】:

    • 这更像是一种解决方法。但是有一种可能:)我还是更喜欢finder的方式:)
    猜你喜欢
    • 2019-09-25
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多