Skip to content

Commit

Permalink
[temp/ai test 🤖] Apply default sort when all provided sort parameters…
Browse files Browse the repository at this point in the history
… are invalid
  • Loading branch information
AlexVanderbist committed May 31, 2024
1 parent 0e7be7b commit 0ddcaab
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/Concerns/SortsQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
});
}

Expand Down
15 changes: 15 additions & 0 deletions tests/SortTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down

0 comments on commit 0ddcaab

Please sign in to comment.