Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort files by DESC order with Symfony Finder Component?

By default Symfony Finder Component sorts files by ASC order.

//sorting by ASC order
$finder->files()->in($this->getDumpPath())->sortByModifiedTime();

How can I sort files by DESC?

like image 218
Victor Bocharsky Avatar asked Sep 24 '14 13:09

Victor Bocharsky


3 Answers

You may use the sort method and give your own sort anonymous function (see Symfony\Component\Finder\Iterator\SortableIterator)

$finder->sort(function ($a, $b) { return strcmp($b->getRealpath(), $a->getRealpath()); });

This is all about sorting tips. It's always the same thing with that kind of job. Please take a look to the usort function.

To be more precise, I've just take a code snipet from Symfony\Component\Finder\Iterator\SortableIterator, and I've reverted the return condition.

like image 73
Yann Eugoné Avatar answered Nov 18 '22 19:11

Yann Eugoné


The reverseSorting method, that was introduced in Symfony 4.2, can be used now.

$finder = new Finder();
$finder->sortByModifiedTime();
$finder->reverseSorting();
$finder->files()->in( $directoryPath );

foreach ($finder as $file) {
  // log each modification time for example 
  // $this->logger->debug ( \date('d/m/Y H:i', $file->getMTime()) );
}

Github commit

like image 40
Stephane BEAUFORT Avatar answered Nov 18 '22 19:11

Stephane BEAUFORT


In Symfony\Component\Finder\Iterator\SortableIterator you can see the ASC case, so the DESC case is:

$finder->files()->in($this->getDumpPath())->sort(
    function ($a, $b) {
       return ($b->getMTime() - $a->getMTime());
    }
);
like image 45
NachoNerd Avatar answered Nov 18 '22 19:11

NachoNerd