From 0ddcaabb17ffb26597ecc35af225a50ec0eec6e3 Mon Sep 17 00:00:00 2001 From: Alex Vanderbist Date: Fri, 31 May 2024 11:49:56 +0200 Subject: [PATCH] =?UTF-8?q?[temp/ai=20test=20=F0=9F=A4=96]=20Apply=20defau?= =?UTF-8?q?lt=20sort=20when=20all=20provided=20sort=20parameters=20are=20i?= =?UTF-8?q?nvalid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Concerns/SortsQuery.php | 7 ++++++- tests/SortTest.php | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/Concerns/SortsQuery.php b/src/Concerns/SortsQuery.php index c61d216f..d74e7385 100644 --- a/src/Concerns/SortsQuery.php +++ b/src/Concerns/SortsQuery.php @@ -69,7 +69,12 @@ protected function addRequestedSortsToQuery(): void $sort = $this->findSort($key); - $sort?->sort($this, $descending); + if (!$sort) { + // Apply default sort if no valid sorts are present in the request + $this->defaultSorts($this->allowedSorts->toArray()); + } else { + $sort->sort($this, $descending); + } }); } diff --git a/tests/SortTest.php b/tests/SortTest.php index 95534beb..caa6f22e 100644 --- a/tests/SortTest.php +++ b/tests/SortTest.php @@ -430,6 +430,21 @@ public function __invoke(Builder $query, bool $descending, string $property): Bu $this->assertSortedDescending($sortedModels, 'name'); }); +// Test for issue resolution +it('applies default sort when all provided sort parameters are invalid', function () { + $request = new Request([ + 'sort' => 'invalid_column', + ]); + + $sortedModels = QueryBuilder::for(TestModel::class, $request) + ->allowedSorts('name') + ->defaultSort('-name') + ->get(); + + // The default sort '-name' should be applied, resulting in models being sorted by 'name' in descending order. + $this->assertSortedDescending($sortedModels, 'name'); +}); + // Helpers function createQueryFromSortRequest(?string $sort = null): QueryBuilder {