Completed
Push — master ( 29e3b2...ea9ad6 )
by
unknown
01:45
created

Sort::custom()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Spatie\QueryBuilder;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Spatie\QueryBuilder\Enums\SortDirection;
7
use Spatie\QueryBuilder\Sorts\SortsField;
8
use Spatie\QueryBuilder\Sorts\Sort as CustomSort;
9
10
class Sort
11
{
12
    /** @var string */
13
    protected $sortClass;
14
15
    /** @var string */
16
    protected $property;
17
18
    /** @var string */
19
    protected $defaultDirection;
20
21
    public function __construct(string $property, $sortClass)
22
    {
23
        $this->property = ltrim($property, '-');
24
        $this->sortClass = $sortClass;
25
        $this->defaultDirection = static::parsePropertyDirection($property);
26
    }
27
28
    public static function parsePropertyDirection(string $property): string
29
    {
30
        return $property[0] === '-' ? SortDirection::DESCENDING : SortDirection::ASCENDING;
31
    }
32
33
    public function sort(Builder $builder, ?bool $descending = null)
34
    {
35
        $sortClass = $this->resolveSortClass();
36
37
        $descending = $descending ?? ($this->defaultDirection === SortDirection::DESCENDING);
38
39
        ($sortClass)($builder, $descending, $this->property);
40
    }
41
42
    public static function field(string $property) : self
43
    {
44
        return new static($property, SortsField::class);
45
    }
46
47
    public static function custom(string $property, $sortClass) : self
48
    {
49
        return new static($property, $sortClass);
50
    }
51
52
    public function getProperty(): string
53
    {
54
        return $this->property;
55
    }
56
57
    public function isForProperty(string $property): bool
58
    {
59
        return $this->property === $property;
60
    }
61
62
    private function resolveSortClass(): CustomSort
63
    {
64
        if ($this->sortClass instanceof CustomSort) {
65
            return $this->sortClass;
66
        }
67
68
        return new $this->sortClass;
69
    }
70
}
71