1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\QueryBuilder; |
4
|
|
|
|
5
|
|
|
use Spatie\QueryBuilder\Enums\SortDirection; |
6
|
|
|
use Spatie\QueryBuilder\Exceptions\InvalidDirection; |
7
|
|
|
use Spatie\QueryBuilder\Sorts\Sort; |
8
|
|
|
use Spatie\QueryBuilder\Sorts\SortsField; |
9
|
|
|
|
10
|
|
|
class AllowedSort |
11
|
|
|
{ |
12
|
|
|
/** @var \Spatie\QueryBuilder\Sorts\Sort */ |
13
|
|
|
protected $sortClass; |
14
|
|
|
|
15
|
|
|
/** @var string */ |
16
|
|
|
protected $name; |
17
|
|
|
|
18
|
|
|
/** @var string */ |
19
|
|
|
protected $defaultDirection; |
20
|
|
|
|
21
|
|
|
/** @var string */ |
22
|
|
|
protected $internalName; |
23
|
|
|
|
24
|
|
|
public function __construct(string $name, Sort $sortClass, ?string $internalName = null) |
25
|
|
|
{ |
26
|
|
|
$this->name = ltrim($name, '-'); |
27
|
|
|
|
28
|
|
|
$this->sortClass = $sortClass; |
29
|
|
|
|
30
|
|
|
$this->defaultDirection = static::parseSortDirection($name); |
31
|
|
|
|
32
|
|
|
$this->internalName = $internalName ?? $this->name; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public static function parseSortDirection(string $name): string |
36
|
|
|
{ |
37
|
|
|
return strpos($name, '-') === 0 ? SortDirection::DESCENDING : SortDirection::ASCENDING; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function sort(QueryBuilder $query, ?bool $descending = null): void |
41
|
|
|
{ |
42
|
|
|
$descending = $descending ?? ($this->defaultDirection === SortDirection::DESCENDING); |
43
|
|
|
|
44
|
|
|
($this->sortClass)($query, $descending, $this->internalName); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public static function field(string $name, ?string $internalName = null): self |
48
|
|
|
{ |
49
|
|
|
return new static($name, new SortsField, $internalName); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public static function custom(string $name, Sort $sortClass, ?string $internalName = null): self |
53
|
|
|
{ |
54
|
|
|
return new static($name, $sortClass, $internalName); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function getName(): string |
58
|
|
|
{ |
59
|
|
|
return $this->name; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
public function isSort(string $sortName): bool |
63
|
|
|
{ |
64
|
|
|
return $this->name === $sortName; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
public function getInternalName(): string |
68
|
|
|
{ |
69
|
|
|
return $this->internalName; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function defaultDirection(string $defaultDirection) |
73
|
|
|
{ |
74
|
|
|
if (! in_array($defaultDirection, [ |
75
|
|
|
SortDirection::ASCENDING, |
76
|
|
|
SortDirection::DESCENDING, |
77
|
|
|
])) { |
78
|
|
|
throw InvalidDirection::make($defaultDirection); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
$this->defaultDirection = $defaultDirection; |
82
|
|
|
|
83
|
|
|
return $this; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|