Page MenuHomeDevCentral

Improve how to scan directory
Open, NormalPublic

Description

Initial issue
Filed on Espace Win Bugzilla 2014-02-12 06:42 UTC.

Use instead glob wrapper instead than scandir, then a get_extension() call on each loop item

Replace the code like:

... = scandir($path);
...
foreach (...) {
    if (get_extension($file) == "json") {
         //Do action
    }
}

By:

$files = new DirectoryIterator("glob://$path/*.json");
foreach ($files as $file) {
    //Do action
}

See http://www.php.net/manual/en/wrappers.glob.php for documentation

To detect it, search scandir.
Results are expected in FilesCollection class, in the Documents application and in the Disclaimer class.

2022-03-19 notes
This is clearly an issue for keruald/omnitools.

I've started in D2500 to refactor search in directory code in Keruald\Omnitools\IO\Directory: https://github.com/keruald/keruald/blob/main/omnitools/src/IO/Directory.php#L61

I forgot about DirectoryIterator and the glob pattern, could be more convenient than the glob() method we wrap.

Related Objects

Event Timeline

dereckson triaged this task as Normal priority.Mar 19 2022, 22:40
dereckson created this task.

I forgot about DirectoryIterator and the glob pattern, could be more convenient than the glob() method we wrap.

In both case, we've to iterate and map into the File class, so the current array_map use is clearly acceptable:

Directory class
public function glob (string $pattern) : array {
    return array_map(
        function ($file) {
            return new File($file);
        }, glob("$this->path/$pattern")
    );
}

In we use DirectoryIterator and the glob wrapper we'd have:

$files = [];
$filesInfo = new DirectoryIterator("glob://$path/*.json");
foreach ($filesInfo as $fileInfo) {
    $files[] = File::fromFileInfo($fileInfo); // method to create
}
return $files;