-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFormatter.php
274 lines (234 loc) · 8.36 KB
/
Formatter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
<?php declare(strict_types = 1);
/**
* This file is part of the SqlFtw library (https://github.com/sqlftw)
*
* Copyright (c) 2017 Vlasta Neubauer (@paranoiq)
*
* For the full copyright and license information read the file 'license.md', distributed with this source code
*/
namespace SqlFtw\Formatter;
use DateTimeInterface;
use Dogma\Arr;
use Dogma\Time\Date;
use Dogma\Time\DateTime;
use Dogma\Time\Time;
use LogicException;
use SqlFtw\Platform\Platform;
use SqlFtw\Session\Session;
use SqlFtw\Sql\Dml\Utility\DelimiterCommand;
use SqlFtw\Sql\Expression\AllLiteral;
use SqlFtw\Sql\Expression\Literal;
use SqlFtw\Sql\Expression\PrimaryLiteral;
use SqlFtw\Sql\Keyword;
use SqlFtw\Sql\SqlMode;
use SqlFtw\Sql\SqlSerializable;
use SqlFtw\Sql\Statement;
use function array_keys;
use function array_map;
use function array_values;
use function get_class;
use function gettype;
use function implode;
use function is_numeric;
use function is_object;
use function is_string;
use function ltrim;
use function preg_match;
use function str_replace;
use function strpos;
use function strtoupper;
class Formatter
{
private const MYSQL_ESCAPES = [
'\\' => '\\\\',
"\x00" => '\0',
"\x08" => '\b',
"\n" => '\n', // 0a
"\r" => '\r', // 0d
"\t" => '\t', // 09
"\x1a" => '\Z', // 1a (legacy Win EOF)
];
private Platform $platform;
private Session $session;
public string $indent;
public bool $comments;
public bool $quoteAllNames;
public bool $escapeWhitespace;
/** @var list<string> */
private array $escapeKeys;
/** @var list<string> */
private array $escapeValues;
/** @var list<string> */
private array $escapeWsKeys;
/** @var list<string> */
private array $escapeWsValues;
public function __construct(
Platform $platform,
Session $session,
string $indent = ' ',
bool $comments = false,
bool $quoteAllNames = false,
bool $escapeWhitespace = true
) {
$this->platform = $platform;
$this->session = $session;
$this->indent = $indent;
$this->comments = $comments;
$this->quoteAllNames = $quoteAllNames;
$this->escapeWhitespace = $escapeWhitespace;
$escapes = self::MYSQL_ESCAPES;
$this->escapeWsKeys = array_keys($escapes);
$this->escapeWsValues = array_values($escapes);
if (!$this->escapeWhitespace) {
unset($escapes["\n"], $escapes["\r"], $escapes["\t"]);
}
$this->escapeKeys = array_keys($escapes);
$this->escapeValues = array_values($escapes);
}
public function getPlatform(): Platform
{
return $this->platform;
}
public function getSession(): Session
{
return $this->session;
}
public function indent(string $code): string
{
return str_replace("\n", "\n\t", $code);
}
public function formatName(string $name): string
{
if ($name === '*') {
return '*';
}
$sqlMode = $this->session->getMode();
$quote = $sqlMode->containsAny(SqlMode::ANSI_QUOTES) ? '"' : '`';
$name = str_replace($quote, $quote . $quote, $name);
$upper = strtoupper($name);
$needsQuoting = $this->quoteAllNames
|| isset($this->platform->reserved[$upper])
|| strpos($name, $quote) !== false // contains quote
|| preg_match('~[\pL_]~u', $name) === 0 // does not contain letters
|| preg_match('~[\pC\pM\pS\pZ\p{Pd}\p{Pe}\p{Pf}\p{Pi}\p{Po}\p{Ps}]~u', ltrim($name, '@')) !== 0; // contains control, mark, symbols, whitespace, punctuation except _
if ($needsQuoting && !$sqlMode->containsAny(SqlMode::NO_BACKSLASH_ESCAPES)) {
$name = str_replace($this->escapeKeys, $this->escapeValues, $name);
}
return $needsQuoting ? $quote . $name . $quote : $name;
}
/**
* @param non-empty-list<string|AllLiteral|PrimaryLiteral> $names
*/
public function formatNamesList(array $names, string $separator = ', '): string
{
return implode($separator, array_map(function ($name): string {
return $name instanceof Literal ? $name->getValue() : $this->formatName($name);
}, $names));
}
/**
* @param scalar|Date|Time|DateTimeInterface|SqlSerializable|null $value
*/
public function formatValue($value): string
{
if ($value === null) {
return Keyword::NULL;
} elseif ($value === true) {
return '1';
} elseif ($value === false) {
return '0';
} elseif (is_string($value)) {
return $this->formatString($value);
} elseif (is_numeric($value)) {
return (string) $value;
} elseif ($value instanceof SqlSerializable) {
return $value->serialize($this);
} elseif ($value instanceof Date) {
return $this->formatDate($value);
} elseif ($value instanceof Time) {
return $this->formatTime($value);
} elseif ($value instanceof DateTimeInterface) {
return $this->formatDateTime($value);
}
throw new LogicException('Unknown type: ' . (is_object($value) ? get_class($value) : gettype($value)));
}
/**
* @param non-empty-list<scalar|Date|Time|DateTimeInterface|SqlSerializable|null> $values
*/
public function formatValuesList(array $values, string $separator = ', '): string
{
return implode($separator, array_map(function ($value): string {
return $this->formatValue($value);
}, $values));
}
public function formatString(string $string): string
{
if (!$this->session->getMode()->containsAny(SqlMode::NO_BACKSLASH_ESCAPES)) {
$string = str_replace($this->escapeKeys, $this->escapeValues, $string);
}
return "'" . str_replace("'", "''", $string) . "'";
}
public function formatStringForceEscapeWhitespace(string $string): string
{
if (!$this->session->getMode()->containsAny(SqlMode::NO_BACKSLASH_ESCAPES)) {
$string = str_replace($this->escapeWsKeys, $this->escapeWsValues, $string);
}
return "'" . str_replace("'", "''", $string) . "'";
}
/**
* @param non-empty-list<string> $strings
*/
public function formatStringList(array $strings, string $separator = ', '): string
{
return implode($separator, array_map(function (string $string): string {
return $this->formatString($string);
}, $strings));
}
/**
* @param non-empty-list<SqlSerializable> $serializables
*/
public function formatSerializablesList(array $serializables, string $separator = ', '): string
{
return implode($separator, array_map(function (SqlSerializable $serializable): string {
return $serializable->serialize($this);
}, $serializables));
}
/**
* @param non-empty-array<string, SqlSerializable> $serializables
*/
public function formatSerializablesMap(array $serializables, string $separator = ', ', string $keyValueSeparator = ' = '): string
{
return implode($separator, Arr::mapPairs($serializables, function (string $key, SqlSerializable $value) use ($keyValueSeparator): string {
return $key . $keyValueSeparator . $value->serialize($this);
}));
}
/**
* @param Date|DateTimeInterface $date
*/
public function formatDate($date): string
{
return "'" . $date->format(Date::DEFAULT_FORMAT) . "'";
}
/**
* @param Time|DateTimeInterface $time
*/
public function formatTime($time): string
{
return "'" . $time->format(Time::DEFAULT_FORMAT) . "'";
}
public function formatDateTime(DateTimeInterface $dateTime): string
{
return "'" . $dateTime->format(DateTime::DEFAULT_FORMAT) . "'";
}
public function serialize(SqlSerializable $serializable, bool $comments = true, string $delimiter = ';'): string
{
if ($serializable instanceof Statement) {
$result = ($comments ? implode('', $serializable->getCommentsBefore()) : '') . $serializable->serialize($this);
if (!$serializable instanceof DelimiterCommand) {
$result .= $serializable->getDelimiter() ?? $delimiter;
}
} else {
$result = $serializable->serialize($this);
}
return $result;
}
}