From aa7958ed772416adc4f72026eed33536cccaf225 Mon Sep 17 00:00:00 2001 From: Robert Fischer Date: Mon, 6 Jun 2022 12:05:46 +0200 Subject: [PATCH] Add methods sortByExtension() + sortBySize() --- src/Symfony/Component/Finder/Finder.php | 32 +++++++++++++++++++ .../Finder/Iterator/SortableIterator.php | 10 ++++++ 2 files changed, 42 insertions(+) diff --git a/src/Symfony/Component/Finder/Finder.php b/src/Symfony/Component/Finder/Finder.php index 459396d139778..7baecdf906260 100644 --- a/src/Symfony/Component/Finder/Finder.php +++ b/src/Symfony/Component/Finder/Finder.php @@ -424,6 +424,22 @@ public function sort(\Closure $closure): static return $this; } + /** + * Sorts files and directories by extension. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sortByExtension(): static + { + $this->sort = Iterator\SortableIterator::SORT_BY_EXTENSION; + + return $this; + } + /** * Sorts files and directories by name. * @@ -456,6 +472,22 @@ public function sortByCaseInsensitiveName(bool $useNaturalSort = false): static return $this; } + /** + * Sorts files and directories by size. + * + * This can be slow as all the matching files and directories must be retrieved for comparison. + * + * @return $this + * + * @see SortableIterator + */ + public function sortBySize(): static + { + $this->sort = Iterator\SortableIterator::SORT_BY_SIZE; + + return $this; + } + /** * Sorts files and directories by type (directories before files), then by name. * diff --git a/src/Symfony/Component/Finder/Iterator/SortableIterator.php b/src/Symfony/Component/Finder/Iterator/SortableIterator.php index 7e2c2ad7b04e5..e8b556502ef81 100644 --- a/src/Symfony/Component/Finder/Iterator/SortableIterator.php +++ b/src/Symfony/Component/Finder/Iterator/SortableIterator.php @@ -29,6 +29,8 @@ class SortableIterator implements \IteratorAggregate public const SORT_BY_NAME_NATURAL = 6; public const SORT_BY_NAME_CASE_INSENSITIVE = 7; public const SORT_BY_NAME_NATURAL_CASE_INSENSITIVE = 8; + public const SORT_BY_EXTENSION = 9; + public const SORT_BY_SIZE = 10; /** @var \Traversable */ private \Traversable $iterator; @@ -83,6 +85,14 @@ public function __construct(\Traversable $iterator, int|callable $sort, bool $re $this->sort = static function (\SplFileInfo $a, \SplFileInfo $b) use ($order) { return $order * ($a->getMTime() - $b->getMTime()); }; + } elseif (self::SORT_BY_EXTENSION === $sort) { + $this->sort = static function (\SplFileInfo $a, \SplFileInfo $b) use ($order) { + return $order * strnatcmp($a->getExtension(), $b->getExtension()); + }; + } elseif (self::SORT_BY_SIZE === $sort) { + $this->sort = static function (\SplFileInfo $a, \SplFileInfo $b) use ($order) { + return $order * ($a->getSize() - $b->getSize()); + }; } elseif (self::SORT_BY_NONE === $sort) { $this->sort = $order; } elseif (\is_callable($sort)) {