1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\QueryBuilder; |
4
|
|
|
|
5
|
|
|
use Spatie\QueryBuilder\Sorts\Sort; |
6
|
|
|
use Spatie\QueryBuilder\Sorts\SortsField; |
7
|
|
|
use Spatie\QueryBuilder\Enums\SortDirection; |
8
|
|
|
|
9
|
|
|
class AllowedSort |
10
|
|
|
{ |
11
|
|
|
/** @var string */ |
12
|
|
|
protected $sortClass; |
13
|
|
|
|
14
|
|
|
/** @var \Spatie\QueryBuilder\Sorts\Sort */ |
15
|
|
|
protected $name; |
16
|
|
|
|
17
|
|
|
/** @var string */ |
18
|
|
|
protected $defaultDirection; |
19
|
|
|
|
20
|
|
|
/** @var string */ |
21
|
|
|
protected $internalName; |
22
|
|
|
|
23
|
|
|
public function __construct(string $name, Sort $sortClass, ?string $internalName = null) |
24
|
|
|
{ |
25
|
|
|
$this->name = ltrim($name, '-'); |
|
|
|
|
26
|
|
|
|
27
|
|
|
$this->sortClass = $sortClass; |
|
|
|
|
28
|
|
|
|
29
|
|
|
$this->defaultDirection = static::parseSortDirection($name); |
30
|
|
|
|
31
|
|
|
$this->internalName = $internalName ?? $this->name; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public static function parseSortDirection(string $name): string |
35
|
|
|
{ |
36
|
|
|
return strpos($name, '-') === 0 ? SortDirection::DESCENDING : SortDirection::ASCENDING; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function sort(QueryBuilder $query, ?bool $descending = null): void |
40
|
|
|
{ |
41
|
|
|
$descending = $descending ?? ($this->defaultDirection === SortDirection::DESCENDING); |
42
|
|
|
|
43
|
|
|
($this->sortClass)($query, $descending, $this->internalName); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public static function field(string $name, ?string $internalName = null) : self |
47
|
|
|
{ |
48
|
|
|
return new static($name, new SortsField, $internalName); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public static function custom(string $name, Sort $sortClass, ?string $internalName = null) : self |
52
|
|
|
{ |
53
|
|
|
return new static($name, $sortClass, $internalName); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
public function getName(): string |
57
|
|
|
{ |
58
|
|
|
return $this->name; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function isSort(string $sortName): bool |
62
|
|
|
{ |
63
|
|
|
return $this->name === $sortName; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
public function getInternalName(): string |
67
|
|
|
{ |
68
|
|
|
return $this->internalName; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.
Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..