Passed
Push — master ( f533bd...3986a9 )
by Ron
02:38
created

DBOrderSpec::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 3
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
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...
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')}>
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...
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