Skip to content

Commit 16aff97

Browse files
committed
[Finder] added "use natural sort" option
1 parent 271331c commit 16aff97

11 files changed

+655
-51
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
CHANGELOG
22
=========
33

4+
4.2.0
5+
-----
6+
7+
* added $useNaturalSort option to Finder::sortByName() method
8+
49
4.0.0
510
-----
611

Finder.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -397,13 +397,17 @@ public function sort(\Closure $closure)
397397
*
398398
* This can be slow as all the matching files and directories must be retrieved for comparison.
399399
*
400+
* @param bool $useNaturalSort Whether to use natural sort or not, disabled by default
401+
*
400402
* @return $this
401403
*
402404
* @see SortableIterator
403405
*/
404-
public function sortByName()
406+
public function sortByName(/* bool $useNaturalSort = false */)
405407
{
406-
$this->sort = Iterator\SortableIterator::SORT_BY_NAME;
408+
$useNaturalSort = 0 < func_num_args() && func_get_arg(0);
409+
410+
$this->sort = $useNaturalSort ? Iterator\SortableIterator::SORT_BY_NAME_NATURAL : Iterator\SortableIterator::SORT_BY_NAME;
407411

408412
return $this;
409413
}

Iterator/SortableIterator.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ class SortableIterator implements \IteratorAggregate
2323
const SORT_BY_ACCESSED_TIME = 3;
2424
const SORT_BY_CHANGED_TIME = 4;
2525
const SORT_BY_MODIFIED_TIME = 5;
26+
const SORT_BY_NAME_NATURAL = 6;
2627

2728
private $iterator;
2829
private $sort;
@@ -41,6 +42,10 @@ public function __construct(\Traversable $iterator, $sort)
4142
$this->sort = function ($a, $b) {
4243
return strcmp($a->getRealpath() ?: $a->getPathname(), $b->getRealpath() ?: $b->getPathname());
4344
};
45+
} elseif (self::SORT_BY_NAME_NATURAL === $sort) {
46+
$this->sort = function ($a, $b) {
47+
return strnatcmp($a->getRealPath() ?: $a->getPathname(), $b->getRealPath() ?: $b->getPathname());
48+
};
4449
} elseif (self::SORT_BY_TYPE === $sort) {
4550
$this->sort = function ($a, $b) {
4651
if ($a->isDir() && $b->isFile()) {

0 commit comments

Comments
 (0)