|
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
|
|
|
|