Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
| Sortable | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
5 | |
100.00% |
1 / 1 |
| processSort | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
5 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace DevToolbelt\LaravelFastCrud\Traits; |
| 6 | |
| 7 | use Illuminate\Database\Eloquent\Builder; |
| 8 | use Illuminate\Support\Str; |
| 9 | |
| 10 | /** |
| 11 | * Provides sorting functionality for Eloquent queries. |
| 12 | * |
| 13 | * Supports multiple columns and ascending/descending order. |
| 14 | * Column names are automatically converted from camelCase to snake_case. |
| 15 | * |
| 16 | * @example |
| 17 | * ``` |
| 18 | * // Single column ascending |
| 19 | * GET /products?sort=name |
| 20 | * |
| 21 | * // Single column descending (prefix with -) |
| 22 | * GET /products?sort=-created_at |
| 23 | * |
| 24 | * // Multiple columns |
| 25 | * GET /products?sort=category,-price,name |
| 26 | * ``` |
| 27 | */ |
| 28 | trait Sortable |
| 29 | { |
| 30 | /** |
| 31 | * Processes sort parameter and applies ORDER BY clauses to the query. |
| 32 | * |
| 33 | * @param Builder $query The query builder instance |
| 34 | * @param string $sort Comma-separated column names (prefix with - for DESC) |
| 35 | */ |
| 36 | public function processSort(Builder $query, string $sort = ''): void |
| 37 | { |
| 38 | if ($sort === '') { |
| 39 | return; |
| 40 | } |
| 41 | |
| 42 | $columns = explode(',', $sort); |
| 43 | |
| 44 | foreach ($columns as $column) { |
| 45 | $column = trim($column); |
| 46 | |
| 47 | if ($column === '') { |
| 48 | continue; |
| 49 | } |
| 50 | |
| 51 | if (str_starts_with($column, '-')) { |
| 52 | $columnName = Str::snake(substr($column, 1)); |
| 53 | $query->orderBy($columnName, 'DESC'); |
| 54 | continue; |
| 55 | } |
| 56 | |
| 57 | $columnName = Str::snake($column); |
| 58 | $query->orderBy($columnName, 'ASC'); |
| 59 | } |
| 60 | } |
| 61 | } |