1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Kir\MySQL\Builder\Expr; |
4
|
|
|
|
5
|
|
|
use RuntimeException; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Defines fields that are sortable. Sortable fields have an alias. |
9
|
|
|
* The alias can be passed as a sort specifier - along with the direction in which to sort. |
10
|
|
|
*/ |
11
|
|
|
class DBOrderSpec implements DBOrderSpecInterface, OrderBySpecification { |
12
|
|
|
/** @var array<string, string> */ |
13
|
|
|
private $sortSpecification; |
14
|
|
|
/** @var array<string, string> */ |
15
|
|
|
private $sortingInstruction; |
16
|
|
|
/** @var array<string, mixed> */ |
17
|
|
|
private $options; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param array<string, string> $sortSpecification |
21
|
|
|
* @param array<string, string> $sortingInstruction |
22
|
|
|
* @param array{max_sort_instructions?: positive-int} $options |
|
|
|
|
23
|
|
|
* @return static |
24
|
|
|
*/ |
25
|
|
|
public static function from(array $sortSpecification, array $sortingInstruction, array $options = []) { |
26
|
|
|
return new static($sortSpecification, $sortingInstruction, $options); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @inheritDoc |
31
|
|
|
*/ |
32
|
|
|
public function __construct(array $sortSpecification, array $sortingInstruction, array $options = []) { |
33
|
|
|
$this->sortSpecification = $sortSpecification; |
34
|
|
|
$this->sortingInstruction = $sortingInstruction; |
35
|
|
|
$this->options = $options; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @return array<int, array{string, string&('ASC'|'DESC')}> |
|
|
|
|
40
|
|
|
*/ |
41
|
|
|
public function getFields(): array { |
42
|
|
|
$fields = []; |
43
|
|
|
$max = $this->options['max_sort_instructions'] ?? 16; |
44
|
|
|
foreach($this->sortingInstruction as $alias => $direction) { |
45
|
|
|
$direction = strtolower($direction) === 'desc' ? 'DESC' : 'ASC'; |
46
|
|
|
if(!array_key_exists($alias, $this->sortSpecification)) { |
47
|
|
|
throw new DBSortAliasNotFoundException('Sorting: Alias for DB-Expression not found'); |
48
|
|
|
} |
49
|
|
|
$fields[] = [$this->sortSpecification[$alias], $direction]; |
50
|
|
|
if($max < 1) { |
51
|
|
|
throw new DBSortTooManyInstructionsException(); |
52
|
|
|
} |
53
|
|
|
$max--; |
54
|
|
|
} |
55
|
|
|
return $fields; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|