Issues (83)

src/Builder/Expr/DBOrderSpec.php (2 issues)

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