Skip to content

Commit

Permalink
Improved sorting of folder files.
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Berthereau authored and Daniel Berthereau committed Sep 27, 2021
1 parent 92a47ba commit 2c95691
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 38 deletions.
31 changes: 12 additions & 19 deletions Module.php
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,9 @@ protected function listFiles(string $directory, bool $recursive = false): array

$listFiles = [];

// To simplify sort.
$listRootFiles = [];

$lengthDir = strlen($this->directory) + 1;
if ($recursive) {
$dir = new \RecursiveDirectoryIterator($directory);
Expand All @@ -221,6 +224,9 @@ protected function listFiles(string $directory, bool $recursive = false): array
$relativePath = substr($filepath, $lengthDir);
// Use keys for quicker process on big directories.
$listFiles[$relativePath] = null;
if (pathinfo($filepath, PATHINFO_DIRNAME) === $directory) {
$listRootFiles[$relativePath] = null;
}
}
}
} else {
Expand All @@ -237,25 +243,12 @@ protected function listFiles(string $directory, bool $recursive = false): array
}
}

// Don't mix directories and files, but list directories first as usual.
$alphabeticAndDirFirst = function ($a, $b) {
// Numeric array keys are number.
$a = (string) $a;
$b = (string) $b;
if ($a === $b) {
return 0;
}
$aInRoot = strpos($a, '/') === false;
$bInRoot = strpos($b, '/') === false;
if (($aInRoot && $bInRoot) || (!$aInRoot && !$bInRoot)) {
return strcasecmp($a, $b);
}
return $bInRoot ? -1 : 1;
};

uksort($listFiles, $alphabeticAndDirFirst);

return array_keys($listFiles);
// Don't mix directories and files. List root files, then sub-folders.
$listFiles = array_keys($listFiles);
natcasesort($listFiles);
$listRootFiles = array_keys($listRootFiles);
natcasesort($listRootFiles);
return array_values(array_unique(array_merge($listRootFiles, $listFiles)));
}

/**
Expand Down
22 changes: 3 additions & 19 deletions src/Media/Ingester/SideloadDir.php
Original file line number Diff line number Diff line change
Expand Up @@ -264,25 +264,9 @@ protected function listDirs(): void
}
}

// Don't mix directories and files, but list directories first as usual.
$alphabeticAndDirFirst = function ($a, $b) {
// Numeric array keys are number.
$a = (string) $a;
$b = (string) $b;
if ($a === $b) {
return 0;
}
$aInRoot = strpos($a, '/') === false;
$bInRoot = strpos($b, '/') === false;
if (($aInRoot && $bInRoot) || (!$aInRoot && !$bInRoot)) {
return strcasecmp($a, $b);
}
return $bInRoot ? -1 : 1;
};

uksort($this->listDirs, $alphabeticAndDirFirst);

$this->listDirs = array_combine(array_keys($this->listDirs), array_keys($this->listDirs));
$this->listDirs = array_keys($this->listDirs);
natcasesort($this->listDirs);
$this->listDirs = array_combine($this->listDirs, $this->listDirs);
}

/**
Expand Down

0 comments on commit 2c95691

Please sign in to comment.