Completed
Push — master ( 5c55d7...79e99a )
by Fèvre
28s queued 15s
created

WithSorting::sortBy()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 7
c 1
b 0
f 0
nc 8
nop 1
dl 0
loc 11
rs 9.2222
1
<?php
2
3
namespace Xetaravel\Http\Livewire\Traits;
4
5
use Illuminate\Contracts\Database\Query\Builder;
6
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
59
    {
60
        return $query->orderBy($this->sortField, $this->sortDirection);
61
    }
62
}
63