LimitBuilder::buildLimit()   B
last analyzed

Complexity

Conditions 7
Paths 10

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 17
rs 8.8333
cc 7
nc 10
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
			return $this->limit->getValue();
16
		}
17
		return $this->limit;
18
	}
19
20
	/**
21
	 * @param null|int|OptionalValue $limit
22
	 * @return $this
23
	 */
24
	public function limit($limit) {
25
		$this->limit = $limit;
26
		return $this;
27
	}
28
29
	/**
30
	 * @param string $query
31
	 * @param int|null $offset
32
	 * @return string
33
	 */
34
	protected function buildLimit(string $query, ?int $offset = null) {
35
		$limit = $this->getLimit();
36
		if($limit === null && $offset !== null) {
37
			$limit = '18446744073709551615';
38
		}
39
		if($this->limit instanceof OptionalValue) {
40
			if($this->limit->isValid()) {
41
				$value = $this->limit->getValue();
42
				if(!preg_match('{\\d+}', $value)) {
43
					throw new InvalidValueException('Value for LIMIT has to be a number');
44
				}
45
				$query .= "LIMIT\n\t{$this->limit->getValue()}\n";
46
			}
47
		} elseif($limit !== null) {
48
			$query .= "LIMIT\n\t{$limit}\n";
49
		}
50
		return $query;
51
	}
52
}
53