Skip to content

Commit

Permalink
Add config to disable InvalidSortQuery exception (#830)
Browse files Browse the repository at this point in the history
* Add config to disable InvalidSortQuery exception

* $sort can be null
  • Loading branch information
bohemima committed Feb 24, 2023
1 parent 44eaa38 commit 7b3911f
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
6 changes: 6 additions & 0 deletions config/query-builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@
*/
'disable_invalid_filter_query_exception' => false,

/*
* By default the package will throw an `InvalidSortQuery` exception when a sort in the
* URL is not allowed in the `allowedSorts()` method.
*/
'disable_invalid_sort_query_exception' => false,

/*
* By default the package inspects query string of request using $request->query().
* You can change this behavior to inspect the request body using $request->input()
Expand Down
6 changes: 5 additions & 1 deletion src/Concerns/SortsQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ protected function addRequestedSortsToQuery()

$sort = $this->findSort($key);

$sort->sort($this, $descending);
$sort?->sort($this, $descending);
});
}

Expand All @@ -99,6 +99,10 @@ protected function findSort(string $property): ?AllowedSort

protected function ensureAllSortsExist(): void
{
if (config('query-builder.disable_invalid_sort_query_exception')) {
return;
}

$requestedSortNames = $this->request->sorts()->map(function (string $sort) {
return ltrim($sort, '-');
});
Expand Down
9 changes: 9 additions & 0 deletions tests/SortTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,15 @@
->allowedSorts('id');
});

it('does not throw invalid sort query exception when disable in config', function () {
config(['query-builder.disable_invalid_sort_query_exception' => true]);

createQueryFromSortRequest('name')
->allowedSorts('id');

expect(true)->toBeTrue();
});

test('an invalid sort query exception contains the unknown and allowed sorts', function () {
$exception = InvalidSortQuery::sortsNotAllowed(collect(['unknown sort']), collect(['allowed sort']));

Expand Down

0 comments on commit 7b3911f

Please sign in to comment.