From 688f6162daeec724c537f9c283092f45b29b05f2 Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Thu, 3 Apr 2014 20:57:06 +0200 Subject: Add sorting to files list, trashbin and public files --- apps/files/lib/helper.php | 55 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 3 deletions(-) (limited to 'apps/files/lib') diff --git a/apps/files/lib/helper.php b/apps/files/lib/helper.php index 0ae87d12fbf..94c7658c9cf 100644 --- a/apps/files/lib/helper.php +++ b/apps/files/lib/helper.php @@ -69,6 +69,32 @@ class Helper } } + /** + * Comparator function to sort files by date + * + * @param \OCP\Files\FileInfo $a file + * @param \OCP\Files\FileInfo $b file + * @return int -1 if $a must come before $b, 1 otherwise + */ + public static function mtimeCmp($a, $b) { + $aTime = $a->getMTime(); + $bTime = $b->getMTime(); + return $aTime - $bTime; + } + + /** + * Comparator function to sort files by size + * + * @param \OCP\Files\FileInfo $a file + * @param \OCP\Files\FileInfo $b file + * @return int -1 if $a must come before $b, 1 otherwise + */ + public static function sizeCmp($a, $b) { + $aSize = $a->getSize(); + $bSize = $b->getSize(); + return $aSize - $bSize; + } + /** * Formats the file info to be returned as JSON to the client. * @@ -120,12 +146,35 @@ class Helper * returns it as a sorted array of FileInfo. * * @param string $dir path to the directory + * @param string $sortAttribute attribute to sort on + * @param bool $sortDescending true for descending sort, false otherwise * @return \OCP\Files\FileInfo[] files */ - public static function getFiles($dir) { + public static function getFiles($dir, $sortAttribute = 'name', $sortDescending = false) { $content = \OC\Files\Filesystem::getDirectoryContent($dir); - usort($content, array('\OCA\Files\Helper', 'fileCmp')); - return $content; + return self::sortFiles($content, $sortAttribute, $sortDescending); + } + + /** + * Sort the given file info array + * + * @param \OCP\Files\FileInfo[] files to sort + * @param string $sortAttribute attribute to sort on + * @param bool $sortDescending true for descending sort, false otherwise + * @return \OCP\Files\FileInfo[] sorted files + */ + public static function sortFiles($files, $sortAttribute = 'name', $sortDescending = false) { + $sortFunc = 'fileCmp'; + if ($sortAttribute === 'mtime') { + $sortFunc = 'mtimeCmp'; + } else if ($sortAttribute === 'size') { + $sortFunc = 'sizeCmp'; + } + usort($files, array('\OCA\Files\Helper', $sortFunc)); + if ($sortDescending) { + $files = array_reverse($files); + } + return $files; } } -- cgit v1.2.3