Here's a great little drop in replacement for FilesystemIterator I wrote to easily Iterate your filesystem, including:
* Sorting - using ArrayIterator
* Regex Matching - using RegexIterator
* Limiting - using LimitIterator
It's fully chainable
<?php
$files = (new AdvancedFilesystemIterator('/path/to/files'))->sortByMTime();
$files = (new AdvancedFilesystemIterator('/path/to/files'))->sortByMTime()->limit(0, 10);
$files = (new AdvancedFilesystemIterator('/path/to/files'))->sortByMTime()->match('/csv$/')->limit(0, 10);
$files = (new AdvancedFilesystemIterator('/path/to/files'))->sortByMTime()->match('/csv$/')->limit(0, 10)->sortByFilename();
$files = (new AdvancedFilesystemIterator('/path/to/files'))->sortByOwner();
foreach ((new AdvancedFilesystemIterator('/path/to/files'))->sortByMTime()->match('/csv$/')->limit(0, 10) AS $file)
{
print $file->getFilename() . "<br>\n";
}
class AdvancedFilesystemIterator extends ArrayIterator
{
public function __construct(string $path, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS)
{
parent::__construct(iterator_to_array(new FilesystemIterator($path, $flags)));
}
public function __call(string $name, array $arguments)
{
if (preg_match('/^sortBy(.*)/', $name, $m)) return $this->sort('get' . $m[1]);
throw new MemberAccessException('Method ' . $methodName . ' not exists');
}
public function sort($method)
{
if (!method_exists('SplFileInfo', $method)) throw new InvalidArgumentException(sprintf('Method "%s" does not exist in SplFileInfo', $method));
$this->uasort(function(SplFileInfo $a, SplFileInfo $b) use ($method) { return (is_string($a->$method()) ? strnatcmp($a->$method(), $b->$method()) : $b->$method() - $a->$method()); });
return $this;
}
public function limit(int $offset = 0, int $limit = -1)
{
return parent::__construct(iterator_to_array(new LimitIterator($this, $offset, $limit))) ?? $this;
}
public function match(string $regex, int $mode = RegexIterator::MATCH, int $flags = 0, int $preg_flags = 0)
{
return parent::__construct(iterator_to_array(new RegexIterator($this, $regex, $mode, $flags, $preg_flags))) ?? $this;
}
}