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

3

6

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?

Bandanna answered 24/9, 2014 at 13:12 Comment(11)
symfony finder component cant do this , you must sort by desc after get resultHandspike
You may also use the sort method and give your own sort anonymous function (see Symfony\Component\Finder\Iterator\SortableIterator)Succinct
@YannEugoné Can you give me code example with anonymous function in my case?Bandanna
$finder->sort(function ($a, $b) { return strcmp($b->getRealpath(), $a->getRealpath()); });Succinct
@Victor You mean by modified time DESC?Standush
@COil, Yes, or at least by filename DESCBandanna
Ok, so @YannEugoné answer seems good. BTW it could be nice to had the feature to the finder component.Standush
I agree with this, as this is not simple to reuse or modify the standard behaviors of the SortableIterator...Succinct
@YannEugoné How you know that in anonymous function passed 2 arguments in your example? I don't understand (Bandanna
This is all about sorting tips. It's always the same thing with that kind of job. Please take a look to fr2.php.net/manual/fr/function.usort.php. But to be more precise, I've just take a code snipet from the Symfony\Component\Finder\Iterator\SortableIterator, and I've reverted the return condition.Succinct
@YannEugoné, Thanks, I understand! Can you post your comment as answer to my question and I accepted it?Bandanna
C
12

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.

Calefactory answered 25/9, 2014 at 12:15 Comment(0)
K
8

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

Knave answered 10/12, 2018 at 12:35 Comment(0)
B
6

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());
    }
);
Baldheaded answered 8/9, 2015 at 17:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.