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