0

I use the Finder of Symfony to search for a specific file name in directories. I need to sort the result by the directory depth. A file with depth 0 (root folder) should be on top, a file with depth 7 should be the very last.

Available sorting mechanism only sort by name and don't consider the directory deepth. E.g. "Sort by name"

$finder->sortByName(true);
a/acme/conf.yaml
conf.yaml
m/conf.yaml
o/data/a/b/c/d/conf.yaml
t/data/conf.yaml
w/data/conf.yaml

I want conf.yaml to be on top, o/data/a/b/c/d/conf.yaml should be at the bottom.

I found an issue in Symfony (https://github.com/symfony/symfony/issues/11289) but no suggestion for a neat sorting method.

pixelbrackets
  • 1,958
  • 19
  • 28

1 Answers1

0

Symfony allows to set up custom sorting mechanisms: https://symfony.com/doc/current/components/finder.html#sorting-results

To compare the depth I count the slashes in the path and sort the count as suggested in this answer: https://stackoverflow.com/a/2852918/3894752

This should be sufficient enough for directory depths (< 64-bit).

If two files have the same depth, then the filename is used for sorting again.

$finder->sort(static function (\SplFileInfo $a, \SplFileInfo $b) {
    $depth = substr_count($a->getRealPath(), '/') - substr_count($b->getRealPath(), '/');
    return ($depth === 0)? strcmp($a->getRealPath(), $b->getRealPath()) : $depth;
});
conf.yaml
m/conf.yaml
a/acme/conf.yaml
t/data/conf.yaml
w/data/conf.yaml
o/data/a/b/c/d/conf.yaml
pixelbrackets
  • 1,958
  • 19
  • 28