From 3a7d6fc1de6fed156b93091b1f37a82e15b89674 Mon Sep 17 00:00:00 2001 From: Duncan McClean Date: Fri, 18 Oct 2024 20:02:47 +0100 Subject: [PATCH] [5.x] Allow sorting folders in asset browser (#10935) --- src/Assets/AssetFolder.php | 11 +++++++++++ .../CP/Assets/BrowserController.php | 19 +++++++++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/Assets/AssetFolder.php b/src/Assets/AssetFolder.php index 2e96f11a92..40932a1f20 100644 --- a/src/Assets/AssetFolder.php +++ b/src/Assets/AssetFolder.php @@ -97,6 +97,17 @@ public function lastModified() return $date; } + public function size() + { + $size = 0; + + foreach ($this->assets() as $asset) { + $size += $asset->size(); + } + + return $size; + } + public function save() { $this->disk()->put($this->path().'/.gitkeep', ''); diff --git a/src/Http/Controllers/CP/Assets/BrowserController.php b/src/Http/Controllers/CP/Assets/BrowserController.php index 9d5493fcb8..2f1c058f26 100644 --- a/src/Http/Controllers/CP/Assets/BrowserController.php +++ b/src/Http/Controllers/CP/Assets/BrowserController.php @@ -4,6 +4,7 @@ use Illuminate\Http\Request; use Illuminate\Pagination\Paginator; +use Statamic\Assets\AssetFolder; use Statamic\Contracts\Assets\AssetContainer as AssetContainerContract; use Statamic\Exceptions\AuthorizationException; use Statamic\Facades\Asset; @@ -90,10 +91,24 @@ public function folder(Request $request, $container, $path = '/') if ($page >= $lastFolderPage) { $query = $folder->queryAssets(); - if ($request->sort) { + if ($sort = $request->sort) { + $sortByMethod = $request->order === 'desc' ? 'sortByDesc' : 'sortBy'; + + $folders = $folders->$sortByMethod( + fn (AssetFolder $folder) => method_exists($folder, $sort) ? $folder->$sort() : $folder->basename() + ); + $query->orderBy($request->sort, $request->order ?? 'asc'); } else { - $query->orderBy($container->sortField(), $container->sortDirection()); + $sort = $container->sortField(); + $order = $container->sortDirection(); + $sortByMethod = $request->order === 'desc' ? 'sortByDesc' : 'sortBy'; + + $folders = $folders->$sortByMethod( + fn (AssetFolder $folder) => method_exists($folder, $sort) ? $folder->$sort() : $folder->basename() + ); + + $query->orderBy($sort, $order); } $this->applyQueryScopes($query, $request->all());