OffsetBuilder   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 11
eloc 24
c 2
b 0
f 0
dl 0
loc 49
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getOffset() 0 9 3
A offset() 0 3 1
B buildOffset() 0 19 7
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 OffsetBuilder {
8
	private null|int|OptionalValue $offset = null;
9
10
	/**
11
	 * @return null|int
12
	 */
13
	protected function getOffset(): ?int {
14
		if($this->offset instanceof OptionalValue) {
15
			$value = $this->offset->getValue();
16
			if(is_numeric($value)) {
17
				return (int) $value;
18
			}
19
			return null;
20
		}
21
		return $this->offset;
22
	}
23
24
	/**
25
	 * @param null|int|OptionalValue $offset
26
	 * @return $this
27
	 */
28
	public function offset($offset = 0) {
29
		$this->offset = $offset;
30
		return $this;
31
	}
32
33
	/**
34
	 * @param string $query
35
	 * @return string
36
	 */
37
	protected function buildOffset(string $query): string {
38
		$offset = $this->getOffset();
39
		if($this->offset instanceof OptionalValue) {
40
			if($this->offset->isValid()) {
41
				$value = $this->offset->getValue();
42
				if($value === null || is_scalar($value)) {
43
					$value = (string) $value;
44
				} else {
45
					throw new InvalidValueException('Value for OFFSET has to be a number');
46
				}
47
				if(!preg_match('{^\\d+$}', $value)) {
48
					throw new InvalidValueException('Value for OFFSET has to be a number');
49
				}
50
				$query .= "OFFSET\n\t{$value}\n";
51
			}
52
		} elseif($offset !== null) {
53
			$query .= "OFFSET\n\t{$this->offset}\n";
54
		}
55
		return $query;
56
	}
57
}
58