From 0ddcaabb17ffb26597ecc35af225a50ec0eec6e3 Mon Sep 17 00:00:00 2001 From: Alex Vanderbist Date: Fri, 31 May 2024 11:49:56 +0200 Subject: [PATCH 1/2] =?UTF-8?q?[temp/ai=20test=20=F0=9F=A4=96]=20Apply=20d?= =?UTF-8?q?efault=20sort=20when=20all=20provided=20sort=20parameters=20are?= =?UTF-8?q?=20invalid?= 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 { From 19b16cc4b720e5fe5387aaf7464db537015e62e7 Mon Sep 17 00:00:00 2001 From: AlexVanderbist Date: Fri, 31 May 2024 09:50:12 +0000 Subject: [PATCH 2/2] Fix styling --- src/Concerns/SortsQuery.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Concerns/SortsQuery.php b/src/Concerns/SortsQuery.php index d74e7385..e96e5a6c 100644 --- a/src/Concerns/SortsQuery.php +++ b/src/Concerns/SortsQuery.php @@ -69,7 +69,7 @@ protected function addRequestedSortsToQuery(): void $sort = $this->findSort($key); - if (!$sort) { + if (! $sort) { // Apply default sort if no valid sorts are present in the request $this->defaultSorts($this->allowedSorts->toArray()); } else {