Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[temp/ai test 🤖] Apply default sort when all provided sort parameters are invalid #945

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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