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