InsertUpdateStatement::buildFieldList()   B
last analyzed

Complexity

Conditions 8
Paths 11

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 27
rs 8.4444
c 0
b 0
f 0
cc 8
nc 11
nop 2
1
<?php
2
3
namespace Kir\MySQL\Builder;
4
5
use Kir\MySQL\Builder\Internal\DefaultValue;
6
use Kir\MySQL\Builder\Internal\Types;
7
8
/**
9
 * @phpstan-import-type DBParameterValueType from Types
10
 */
11
abstract class InsertUpdateStatement extends Statement {
12
	/** @var array<int, string> */
13
	private ?array $mask = null;
14
15
	/**
16
	 * @return array<int, string>|null
17
	 */
18
	public function getMask(): ?array {
19
		return $this->mask;
20
	}
21
22
	/**
23
	 * @param array<int, string> $mask
24
	 * @return $this
25
	 */
26
	public function setMask(array $mask) {
27
		$this->mask = $mask;
28
29
		return $this;
30
	}
31
32
	/**
33
	 * @param array<int|string, DBParameterValueType> $fields
34
	 * @param array<int, string> $query
35
	 * @return string[]
36
	 */
37
	protected function buildFieldList(array $fields, array $query = []): array {
38
		foreach($fields as $fieldName => $fieldValue) {
39
			if($fieldValue instanceof DefaultValue) {
40
				$fieldValue = 'DEFAULT';
41
			}
42
			if(is_array($this->mask) && !in_array($fieldName, $this->mask, true)) {
43
				continue;
44
			}
45
			if(is_int($fieldName)) {
46
				if(is_array($fieldValue)) {
47
					// @phpstan-ignore-next-line
48
					$fieldValue = $this->db()->quoteExpression($fieldValue[0], array_slice($fieldValue, 1));
49
				}
50
				// @phpstan-ignore-next-line
51
				$query[] = "\t{$fieldValue}";
52
			} else {
53
				$fieldName = $this->db()->quoteField($fieldName);
54
				if(is_array($fieldValue)) {
55
					// @phpstan-ignore-next-line
56
					$fieldValue = $this->db()->quoteExpression($fieldValue[0], array_slice($fieldValue, 1));
57
				}
58
				// @phpstan-ignore-next-line
59
				$query[] = "\t{$fieldName}={$fieldValue}";
60
			}
61
		}
62
63
		return $query;
64
	}
65
66
	/**
67
	 * @param string $fieldName
68
	 * @param array<int, string> $tableFields
69
	 * @return bool
70
	 */
71
	protected function isFieldAccessible(string $fieldName, array $tableFields): bool {
72
		if(!in_array($fieldName, $tableFields)) {
73
			return false;
74
		}
75
		if(!is_array($this->mask)) {
76
			return true;
77
		}
78
79
		return in_array($fieldName, $this->mask, true);
80
	}
81
}
82