symfony: Finder excluded does NOT exclude relative directories

Symfony version(s) affected

5.4+

Description

I’m configuring php-cs-fixer which uses the symfony/finder component and noticed it does not work as advertised.

$finder = PhpCsFixer\Finder::create()
    ->in(__DIR__)
    ->exclude('storage')
;

Will exclude all files that have /storage/ in its path, such as "resources/lang/de/storage/index.php".

Looking at the source it’s quite obvious:

        $iterator = new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs);

        if ($exclude) {
            $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $exclude);
        }

https://github.com/symfony/symfony/blob/6.1/src/Symfony/Component/Finder/Finder.php#L735

and going inside:

        $this->isRecursive = $iterator instanceof \RecursiveIterator;
        // ...
		foreach ($directories as $directory) {
            $directory = rtrim($directory, '/');
            if (!$this->isRecursive || str_contains($directory, '/')) { // <---- $this->isRecursive is always true
                $patterns[] = preg_quote($directory, '#');
            } else {
                $this->excludedDirs[$directory] = true;
            }
        }

How to reproduce

Have dir structure

/ex/should-be-excluded.php
/not/ex/should-be-included.php
.php-cs-fixer.php
# .php-cs-fixer.php
$finder = PhpCsFixer\Finder::create()
    ->in(__DIR__)
    ->exclude('ex')
;

$a = [];
foreach ($finder as $item) {
    $a[] = $item->getRelativePathname();
}
saged($a, count($a));

Possible Solution

No response

Additional Context

symfony/finder in my vendors directory reports itself as v5.4

relevant docs: https://symfony.com/doc/current/components/finder.html#location image

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 1
  • Comments: 18 (3 by maintainers)

Commits related to this issue

Most upvoted comments

That’s a nice bot, here’s a ⚙, good boy, carson!

The feature is still relevant and unsolved 😃

This seems to be similar territory as #28158.