OffsetBuilder::buildOffset()   B
last analyzed

Complexity

Conditions 7
Paths 6

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
dl 0
loc 20
rs 8.8333
c 2
b 0
f 0
cc 7
nc 6
nop 1
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 OffsetBuilder {
9
	private null|int|OptionalValue $offset = null;
10
11
	/**
12
	 * @return null|int
13
	 */
14
	protected function getOffset(): ?int {
15
		if($this->offset instanceof OptionalValue) {
16
			$value = $this->offset->getValue();
17
			if(is_numeric($value)) {
18
				return (int) $value;
19
			}
20
21
			return null;
22
		}
23
24
		return $this->offset;
25
	}
26
27
	/**
28
	 * @param null|int|OptionalValue $offset
29
	 * @return $this
30
	 */
31
	public function offset($offset = 0) {
32
		$this->offset = $offset;
33
34
		return $this;
35
	}
36
37
	/**
38
	 * @param string $query
39
	 * @return string
40
	 */
41
	protected function buildOffset(string $query): string {
42
		$offset = $this->getOffset();
43
		if($this->offset instanceof OptionalValue) {
44
			if($this->offset->isValid()) {
45
				$value = $this->offset->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 .= "OFFSET\n\t{$value}\n";
55
			}
56
		} elseif($offset !== null) {
57
			$query .= "OFFSET\n\t{$this->offset}\n";
58
		}
59
60
		return $query;
61
	}
62
}
63