Skip to content

Commit

Permalink
fix: adding natural sort filter (#586)
Browse files Browse the repository at this point in the history
  • Loading branch information
binaryk committed Sep 7, 2023
1 parent bbb64ae commit 528b2dc
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Filters/Sorts/NaturalSortFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Binaryk\LaravelRestify\Filters\Sorts;

class NaturalSortFilter
{
public function __invoke($request, $query, $value, string $column): void
{
$query->orderByRaw("CAST({$column} AS UNSIGNED) {$value}, {$column} {$value}");
}
}
48 changes: 48 additions & 0 deletions tests/Feature/Filters/SortableFilterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Binaryk\LaravelRestify\Tests\Feature\Filters;

use Binaryk\LaravelRestify\Filters\SortableFilter;
use Binaryk\LaravelRestify\Filters\Sorts\NaturalSortFilter;
use Binaryk\LaravelRestify\Tests\Fixtures\User\User;
use Binaryk\LaravelRestify\Tests\Fixtures\User\UserRepository;
use Binaryk\LaravelRestify\Tests\IntegrationTestCase;
Expand Down Expand Up @@ -33,4 +34,51 @@ public function test_can_order_using_filter_sortable_definition(): void
$this->assertSame('Alisa', $this->getJson(UserRepository::route(query: ['sort' => '-name']))
->json('data.1.attributes.name'));
}

public function test_can_order_using_natural_sortable_filter(): void
{
User::factory()->create([
'name' => '1',
]);

User::factory()->create([
'name' => '10',
]);

User::factory()->create([
'name' => '2',
]);

User::factory()->create([
'name' => '20',
]);

UserRepository::$sort = [
'name' => NaturalSortFilter::class,
];

$this->assertSame('1', $this->getJson(UserRepository::route(query: ['sort' => 'name']))
->json('data.0.attributes.name'));

$this->assertSame('2', $this->getJson(UserRepository::route(query: ['sort' => 'name']))
->json('data.1.attributes.name'));

$this->assertSame('10', $this->getJson(UserRepository::route(query: ['sort' => 'name']))
->json('data.2.attributes.name'));

$this->assertSame('20', $this->getJson(UserRepository::route(query: ['sort' => 'name']))
->json('data.3.attributes.name'));

$this->assertSame('20', $this->getJson(UserRepository::route(query: ['sort' => '-name']))
->json('data.0.attributes.name'));

$this->assertSame('10', $this->getJson(UserRepository::route(query: ['sort' => '-name']))
->json('data.1.attributes.name'));

$this->assertSame('2', $this->getJson(UserRepository::route(query: ['sort' => '-name']))
->json('data.2.attributes.name'));

$this->assertSame('1', $this->getJson(UserRepository::route(query: ['sort' => '-name']))
->json('data.3.attributes.name'));
}
}

0 comments on commit 528b2dc

Please sign in to comment.