LimitBuilder::buildLimit()   B
last analyzed

Complexity

Conditions 9
Paths 12

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
dl 0
loc 23
rs 8.0555
c 1
b 0
f 0
cc 9
nc 12
nop 2
1
<?php
2
3
namespace Kir\MySQL\Builder\Traits;
4
5
use Kir\MySQL\Builder\InvalidValueException;
6
use Kir\MySQL\Builder\Value\OptionalValue;
7
8
trait LimitBuilder {
9
	private null|int|OptionalValue $limit = null;
10
11
	/**
12
	 * @return null|int
13
	 */
14
	protected function getLimit(): ?int {
15
		if($this->limit instanceof OptionalValue) {
16
			$value = $this->limit->getValue();
17
			if(is_numeric($value)) {
18
				return (int) $value;
19
			}
20
21
			return null;
22
		}
23
24
		return $this->limit;
25
	}
26
27
	/**
28
	 * @param null|int|OptionalValue $limit
29
	 * @return $this
30
	 */
31
	public function limit($limit) {
32
		$this->limit = $limit;
33
34
		return $this;
35
	}
36
37
	/**
38
	 * @param string $query
39
	 * @param int|null $offset
40
	 * @return string
41
	 */
42
	protected function buildLimit(string $query, ?int $offset = null) {
43
		$limit = $this->getLimit();
44
		if($limit === null && $offset !== null) {
45
			$limit = '18446744073709551615';
46
		}
47
		if($this->limit instanceof OptionalValue) {
48
			if($this->limit->isValid()) {
49
				$value = $this->limit->getValue();
50
				if($value === null || is_scalar($value)) {
51
					$value = (string) $value;
52
				} else {
53
					throw new InvalidValueException('Value for OFFSET has to be a number');
54
				}
55
				if(!preg_match('{^\\d+$}', $value)) {
56
					throw new InvalidValueException('Value for OFFSET has to be a number');
57
				}
58
				$query .= "LIMIT\n\t{$value}\n";
59
			}
60
		} elseif($limit !== null) {
61
			$query .= "LIMIT\n\t{$limit}\n";
62
		}
63
64
		return $query;
65
	}
66
}
67