LimitBuilder::limit()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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