Listing files of a directory and its subfolders with the Symfony Finder component

Published on 2024-02-13 • Modified on 2024-02-13

In the previous snippet, we saw how to list files of a directory and its subfolders with the RecursiveDirectoryIterator SPL class. Now, let's see an alternative using the Symfony Finder component. Obviously, using the Symfony component makes the code much more concise and readable.


<?php

declare(strict_types=1);

// src/Controller/Snippet/Snippet291Trait.php

namespace App\Controller\Snippet;

use Symfony\Component\Finder\Finder;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet291Trait
{
    public function snippet291(): void
    {
        $baseDir = \dirname(__DIR__);
        $finder = (new Finder())
            ->files()
            ->name('*.php')
            ->in($baseDir)
            ->sortByName()
        ;

        $count = 0;
        foreach ($finder as $file) {
            $pathName = $file->getPathname();
            $pathName = str_replace($baseDir.'/', '', $pathName); // remove base path
            ++$count;

            echo $pathName.PHP_EOL;
        }
        echo PHP_EOL;
        echo 'Number of files: '.$count;

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!