| Total Complexity | 7 |
| Total Lines | 54 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 7 | trait WithSorting |
||
| 8 | { |
||
| 9 | /** |
||
| 10 | * The field to sort by. |
||
| 11 | * |
||
| 12 | * @var string |
||
| 13 | */ |
||
| 14 | public string $sortField = 'created_at'; |
||
| 15 | |||
| 16 | /** |
||
| 17 | * Array of allowed fields. |
||
| 18 | * |
||
| 19 | * @var array |
||
| 20 | */ |
||
| 21 | public array $allowedFields = []; |
||
| 22 | |||
| 23 | /** |
||
| 24 | * The direction of the ordering. |
||
| 25 | * |
||
| 26 | * @var string |
||
| 27 | */ |
||
| 28 | public string $sortDirection = 'desc'; |
||
| 29 | |||
| 30 | /** |
||
| 31 | * Determine the direction regarding of the field. |
||
| 32 | * |
||
| 33 | * @param string $field |
||
| 34 | * |
||
| 35 | * @return void |
||
| 36 | */ |
||
| 37 | public function sortBy(string $field): void |
||
| 38 | { |
||
| 39 | $this->sortDirection = $this->sortField === $field |
||
| 40 | ? $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc' |
||
| 41 | : 'asc'; |
||
| 42 | |||
| 43 | if (empty($this->allowedFields) || |
||
| 44 | in_array($field, $this->allowedFields) || |
||
| 45 | $this->sortField === $field |
||
| 46 | ) { |
||
| 47 | $this->sortField = $field; |
||
| 48 | } |
||
| 49 | } |
||
| 50 | |||
| 51 | /** |
||
| 52 | * Apply the orderBy condition with he field and the direction to the query. |
||
| 53 | * |
||
| 54 | * @param Builder $query The query to apply the orderBy close. |
||
| 55 | * |
||
| 56 | * @return Builder |
||
| 57 | */ |
||
| 58 | public function applySorting(Builder $query): Builder |
||
| 61 | } |
||
| 62 | } |
||
| 63 |