MySQLQuoter::quote()   B
last analyzed

Complexity

Conditions 10
Paths 9

Size

Total Lines 30
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 30
rs 7.6666
cc 10
nc 9
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Kir\MySQL\Databases\MySQL;
4
5
use DateTimeImmutable;
6
use DateTimeInterface;
7
use DateTimeZone;
8
use Kir\MySQL\Builder\DBExpr;
9
use Kir\MySQL\Builder\Select;
10
use PDO;
11
12
class MySQLQuoter {
13
	public function __construct(
14
		private PDO $pdo,
15
		private DateTimeZone $timeZone,
16
	) {}
17
18
	/**
19
	 * @param null|scalar|array<int, null|scalar>|DBExpr|Select|DateTimeInterface $value
20
	 * @return string
21
	 */
22
	public function quote($value): string {
23
		if(is_null($value)) {
24
			return 'NULL';
25
		}
26
27
		if(is_bool($value)) {
28
			return $value ? '1' : '0';
29
		}
30
31
		if(is_array($value)) {
32
			return implode(', ', array_map([$this, __FUNCTION__], $value));
33
		}
34
35
		if($value instanceof DBExpr) {
36
			return $value->getExpression();
37
		}
38
39
		if($value instanceof Select) {
40
			return sprintf('(%s)', (string) $value);
41
		}
42
43
		if(is_int($value) || is_float($value)) {
44
			return (string) $value;
45
		}
46
47
		if($value instanceof DateTimeInterface) {
48
			$value = (new DateTimeImmutable($value->format('c')))->setTimezone($this->timeZone)->format('Y-m-d H:i:s');
49
		}
50
51
		return $this->pdo->quote($value);
52
	}
53
54
	/**
55
	 * @param string $expression
56
	 * @param array<int, null|scalar|array<int, string>|DBExpr|Select> $arguments
57
	 * @return string
58
	 */
59
	public function quoteExpression(string $expression, array $arguments = []): string {
60
		$index = -1;
61
		$func = function() use ($arguments, &$index) {
62
			$index++;
63
			if(array_key_exists($index, $arguments)) {
64
				$argument = $arguments[$index];
65
				$value = $this->quote($argument);
66
			} elseif(count($arguments) > 0) {
67
				$args = $arguments;
68
				$value = array_pop($args);
69
				$value = $this->quote($value);
70
			} else {
71
				$value = 'NULL';
72
			}
73
74
			return $value;
75
		};
76
77
		return (string) preg_replace_callback('{(\\?)}', $func, $expression);
78
	}
79
}
80