LimitBuilder::buildLimit()   B
last analyzed

Complexity

Conditions 9
Paths 12

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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