Skip to content

Commit

Permalink
added Finder::sortByName()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Oct 13, 2022
1 parent 24b2086 commit 8188eb1
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/Utils/Finder.php
Expand Up @@ -30,6 +30,7 @@ class Finder implements \IteratorAggregate
private array $batches = [];
private FinderBatch $batch;
private bool $selfFirst = true;
private bool $sort = false;
private int $maxDepth = -1;
private bool $ignoreUnreadableDirs = true;

Expand Down Expand Up @@ -168,6 +169,13 @@ public function ignoreUnreadableDirs(bool $state = true): static
}


public function sortByName(bool $state = true): static
{
$this->sort = $state;
return $this;
}


/**
* Starts defining a new search group.
*/
Expand Down Expand Up @@ -295,6 +303,11 @@ public function toArray(): array
public function getIterator(): \Generator
{
$groups = $this->prepare();

if ($this->sort) {
ksort($groups, SORT_NATURAL);
}

foreach ($groups as $dir => $searches) {
yield from $this->traverseDir($dir, $searches);
}
Expand Down Expand Up @@ -323,6 +336,11 @@ private function traverseDir(string $dir, array $searches, array $subDirs = []):
}
}

if ($this->sort) {
$items = iterator_to_array($items);
natsort($items);
}

$relativePath = implode(DIRECTORY_SEPARATOR, $subDirs);

foreach ($items as $pathName) {
Expand Down
69 changes: 69 additions & 0 deletions tests/Utils/Finder.sort.phpt
@@ -0,0 +1,69 @@
<?php

/**
* Test: Nette\Utils\Finder sorting.
*/

declare(strict_types=1);

use Nette\Utils\Finder;
use Tester\Assert;


require __DIR__ . '/../bootstrap.php';


function export($iterator)
{
$arr = [];
foreach ($iterator as $key => $value) {
$arr[] = strtr($key, '\\', '/');
}

return $arr;
}


test('basic', function () {
$finder = Finder::find('*')
->from('files')
->sortByName();

Assert::same([
'files/file.txt',
'files/images',
'files/images/logo.gif',
'files/subdir',
'files/subdir/file.txt',
'files/subdir/readme',
'files/subdir/subdir2',
'files/subdir/subdir2/file.txt',
], export($finder));

$finder->childFirst();
Assert::same([
'files/file.txt',
'files/images/logo.gif',
'files/images',
'files/subdir/file.txt',
'files/subdir/readme',
'files/subdir/subdir2/file.txt',
'files/subdir/subdir2',
'files/subdir',
], export($finder));
});


test('and', function () {
$finder = Finder::find('*')->in('files/subdir')
->and()
->files('*')->in('files/images')
->sortByName();

Assert::same([
'files/images/logo.gif',
'files/subdir/file.txt',
'files/subdir/readme',
'files/subdir/subdir2',
], export($finder));
});

0 comments on commit 8188eb1

Please sign in to comment.