1

Is there a way to exclude folders missing some files?

E.g. I have folders like:

FolderA
    aaa.php
    bbb.php
    ccc.php

FolderB
    aaa.php
    bbb.php
    ccc.php

FolderC
    aaa.php

FolderD
    aaa.php
    bbb.php
    ccc.php

I only want to have FolderA, FolderB and FolderD (or exclude FolderC) because FolderC does not have all expected files.

Current Source

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

Current Output:

array(
    [0] => FolderA
    [1] => FolderB
    [2] => FolderC
    [3] => FolderD
)
Dwza
  • 6,494
  • 6
  • 41
  • 73

1 Answers1

1

A naive approach:

<?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);

It will output this:

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

If you want folders to be ordered, simply call sort($dirs); after the foreach block.

A.L
  • 10,259
  • 10
  • 67
  • 98
  • 1
    This more kind of a workaround. But a possibility :) I still would prefer a `finder` way :) – Dwza May 11 '18 at 16:30