1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Stratadox\Sorting; |
5
|
|
|
|
6
|
|
|
use Stratadox\Sorting\Contracts\ExtensibleSorting; |
7
|
|
|
use Stratadox\Sorting\Contracts\Sorting; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Sort according to this definition. |
11
|
|
|
* |
12
|
|
|
* Contains the field, the sorting direction and the sorting definition for |
13
|
|
|
* unresolved elements. |
14
|
|
|
* |
15
|
|
|
* @author Stratadox |
16
|
|
|
* @package Stratadox\Sorting |
17
|
|
|
*/ |
18
|
|
|
final class Sort implements ExtensibleSorting |
19
|
|
|
{ |
20
|
|
|
private $field; |
21
|
|
|
private $ascends; |
22
|
|
|
private $next; |
23
|
|
|
|
24
|
|
|
private function __construct( |
25
|
|
|
string $field, |
26
|
|
|
bool $ascends, |
27
|
|
|
Sorting $next |
28
|
|
|
) { |
29
|
|
|
$this->field = $field; |
30
|
|
|
$this->ascends = $ascends; |
31
|
|
|
$this->next = $next; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public static function descendingBy( |
35
|
|
|
string $field, |
36
|
|
|
Sorting $next = null |
37
|
|
|
): ExtensibleSorting { |
38
|
|
|
return new Sort($field, false, $next ?: NoSorting::needed()); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public static function ascendingBy( |
42
|
|
|
string $field, |
43
|
|
|
Sorting $next = null |
44
|
|
|
): ExtensibleSorting { |
45
|
|
|
return new Sort($field, true, $next ?: NoSorting::needed()); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public function field(): string |
49
|
|
|
{ |
50
|
|
|
return $this->field; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function next(): Sorting |
54
|
|
|
{ |
55
|
|
|
return $this->next; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
public function ascends(): bool |
59
|
|
|
{ |
60
|
|
|
return $this->ascends; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function isRequired(): bool |
64
|
|
|
{ |
65
|
|
|
return true; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
public function andThenAscendingBy(string $field): ExtensibleSorting |
69
|
|
|
{ |
70
|
|
|
// @todo this skips custom non-null Sorting definitions, fix somehow |
71
|
|
|
return new Sort( |
72
|
|
|
$this->field, |
73
|
|
|
$this->ascends, |
74
|
|
|
$this->next instanceof ExtensibleSorting ? |
75
|
|
|
$this->next->andThenAscendingBy($field) : |
|
|
|
|
76
|
|
|
Sort::ascendingBy($field) |
77
|
|
|
); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
public function andThenDescendingBy(string $field): ExtensibleSorting |
81
|
|
|
{ |
82
|
|
|
// @todo this skips custom non-null Sorting definitions, fix somehow |
83
|
|
|
return new Sort( |
84
|
|
|
$this->field, |
85
|
|
|
$this->ascends, |
86
|
|
|
$this->next instanceof ExtensibleSorting ? |
87
|
|
|
$this->next->andThenDescendingBy($field) : |
|
|
|
|
88
|
|
|
Sort::descendingBy($field) |
89
|
|
|
); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|