|
| 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}> |
| 40 | + */ |
| 41 | + public function getFields() { |
| 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 | + $fields[] = [$this->sortSpecification[$alias], $direction]; |
| 48 | + } |
| 49 | + if($max < 1) { |
| 50 | + throw new RuntimeException(); |
| 51 | + } |
| 52 | + $max--; |
| 53 | + } |
| 54 | + return $fields; |
| 55 | + } |
| 56 | +} |
0 commit comments