Skip to content

Commit

Permalink
Allow ordering of nulls to be overridden when sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
rbibby committed Jun 29, 2022
1 parent efb8a86 commit 495dc65
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/Sieve.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ class Sieve

protected $defaultSort = null;

protected $sortable = [];

public function __construct(Request $request)
{
$this->request = $request;
Expand All @@ -37,7 +39,7 @@ public function getFilters()
public function apply($queryBuilder)
{
foreach ($this->getFilters() as $sieveFilter) {
/** @var Filter */
/** @var ModifiesQueries */
$filter = $sieveFilter['filter'];
$property = $sieveFilter['property'];

Expand Down Expand Up @@ -77,6 +79,16 @@ public function apply($queryBuilder)
if ($this->getSort() == "$property:asc") {
$queryBuilder->orderBy($column, "asc");
}

if ($this->getSort() == "$property:asc_nulls_last") {
$queryBuilder->orderByRaw("ISNULL(\"$column\") asc")
->orderBy($column, 'asc');
}

if ($this->getSort() == "$property:desc_nulls_first") {
$queryBuilder->orderByRaw("ISNULL(\"$column\") desc")
->orderBy($column, 'desc');
}
}

return $this;
Expand Down
48 changes: 48 additions & 0 deletions tests/SieveTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,54 @@ public function applies_sieve_sorts_to_a_query_builder_asc()
);
}

/**
* @test
*/
public function applies_sieve_sorts_to_a_query_builder_asc_nulls_last()
{
$request = Request::create('/', 'GET', [
'sort' => 'name:asc_nulls_last',
]);

$seive = new Sieve($request);
$seive->addFilter('name', new StringFilter);

/** @var Builder */
$builder = $this->app->make(Builder::class);
$builder->from('pets');

$seive->apply($builder);

$this->assertEquals(
'select * from "pets" order by ISNULL("name") asc, "name" asc',
$builder->toSql()
);
}

/**
* @test
*/
public function applies_sieve_sorts_to_a_query_builder_desc_nulls_first()
{
$request = Request::create('/', 'GET', [
'sort' => 'name:desc_nulls_first',
]);

$seive = new Sieve($request);
$seive->addFilter('name', new StringFilter);

/** @var Builder */
$builder = $this->app->make(Builder::class);
$builder->from('pets');

$seive->apply($builder);

$this->assertEquals(
'select * from "pets" order by ISNULL("name") desc, "name" desc',
$builder->toSql()
);
}

/**
* @test
*/
Expand Down

0 comments on commit 495dc65

Please sign in to comment.