Passed
Push — shop ( 5180ff...89f6e7 )
by Fèvre
05:07
created

WithSorting::sortBy()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 7
rs 10
1
<?php
2
3
namespace Xetaravel\Http\Livewire\Datatable;
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 = 'id';
15
16
    /**
17
     * The direction of the ordering.
18
     *
19
     * @var string
20
     */
21
    public string $sortDirection = 'asc';
22
23
    /**
24
     * Determine the direction regarding of the field.
25
     *
26
     * @param string $field
27
     *
28
     * @return void
29
     */
30
    public function sortBy(string $field): void
31
    {
32
        $this->sortDirection = $this->sortField === $field
33
            ? $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc'
34
            : 'asc';
35
36
        $this->sortField = $field;
37
    }
38
39
    /**
40
     * Apply the orderBy condition witht he field and the direction to the query.
41
     *
42
     * @param Builder $query The query to apply the orderBy close.
43
     *
44
     * @return Builder
45
     */
46
    public function applySorting(Builder $query): Builder
47
    {
48
        return $query->orderBy($this->sortField, $this->sortDirection);
49
    }
50
}
51