I am using the Symfony Finder
to get all the files with a certain extension and all the directories in a specific directory.
protected function getDirectoryContent(string $directory): array
{
$finder = Finder::create()
->in($directory)
->depth(0)
->name(['*.json', '*.php'])
->sortByName();
return iterator_to_array($finder, true);
}
In this way, this method returns only all the files with extension .php
or .json
within a certain directory. For example, the directory structure I am looking in is the following:
/my/directory/
├── A
├── A.JSON
├── anotherfile.kas
├── file0.ds
├── file1.json
├── file2.php
├── file3.php
├── B
└── C
A
, B
and C
are directories.
When I pass the above directory path
as the $directory
argument in the method I showed above, I get an array with the following elements:
file1.json
file2.php
file3.php
Great!, but my question is, how could I also add all the directories
to the resulting array? My expectations are to get an array like the following:
A
B
C
file1.json
file2.php
file3.php
In you case, you speak to finder:
As result it's wrong, because these two rules contradict each other - because you want search only files.
But, symfony finder can use CallbackIterator
with filter model. In this situation you can add many rules or condition. In you example:
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));
In this case, you speak:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.