Skip to content

Instantly share code, notes, and snippets.

@DragonBe
Created June 22, 2017 21:23
Show Gist options
  • Save DragonBe/63fb1a8d4d28e0b25a3234fe56093615 to your computer and use it in GitHub Desktop.
Save DragonBe/63fb1a8d4d28e0b25a3234fe56093615 to your computer and use it in GitHub Desktop.
Sortable DirectoryIterator based on last modification time
class SortableDirectoryIterator extends RecursiveDirectoryIterator
{
/**
* \ArrayObject
*/
private $dirArray;
public function __construct(string $path)
{
parent::__construct($path);
$this->dirArray = new \ArrayObject();
foreach($this as $item) {
$this->dirArray->append( $item );
}
$this->dirArray->uasort( function ($fileObj1, $fileObj2) {
if ($fileObj1->getMTime() == $fileObj2->getMTime()) {
return 0;
}
return ($fileObj1->getMTime() < $fileObj2->getMTime()) ? -1 : 1;
} );
}
public function getIterator()
{
return $this->dirArray->getIterator();
}
}
@heiglandreas
Copy link

heiglandreas commented Jun 23, 2017

composer require org_heigl/filefinder
$finder = new \Org_Heigl\FileFinder\FileFinder();
$finder->addDirectory($dir);
$list = $finder->find()
$list->sort(new \Org_Heigl\FileFinder\Sorter\MTime());

$list should now be iterable, contain all files recursively within $dir sorted by their mtime…

There's also the possibility to filter or sort the files by different parameters. More info in the README

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment