Passed
Push — master ( e680d4...0c776b )
by Ron
01:59
created

MySQLQuoter   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 14
eloc 34
c 1
b 0
f 0
dl 0
loc 69
rs 10

3 Methods

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