这是一个我编写的小巧的 FilesystemIterator 替代品,它可以轻松地迭代您的文件系统,包括
* 排序 - 使用 ArrayIterator
* 正则表达式匹配 - 使用 RegexIterator
* 限制 - 使用 LimitIterator
它是完全可链接的
<?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;
}
}