-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParser.php
450 lines (407 loc) · 14 KB
/
Parser.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
<?php
/**
* This Software is part of aryelgois/yasql-php and is provided "as is".
*
* @see LICENSE
*/
namespace aryelgois\YaSql;
use Symfony\Component\Yaml\Yaml;
/**
* Create SQL database schemas with YAML
*
* Controller class to simplify the package usage
*
* @author Aryel Mota Góis
* @license MIT
* @link https://www.github.com/aryelgois/yasql-php
*/
class Parser
{
/**
* Identifier patterns accepted in a SQL
*
* @see https://dev.mysql.com/doc/refman/5.7/en/identifiers.html
*
* @var string[]
*/
const IDENTIFIER_PATTERNS = [
'unquoted' => '[0-9a-zA-Z$_\x{0080}-\x{FFFF}]',
'quoted' => '[\x{0001}-\x{007F}\x{0080}-\x{FFFF}]'
];
/**
* Set of Index keywords
*
* The value determines if a table can have one or more indexes
*
* @var string
*/
const INDEX_KEYWORDS = [
'INDEX' => 'multiple',
'PRIMARY' => 'single',
'UNIQUE' => 'multiple',
];
/**
* Types which receive the UNSIGNED attribute
*
* @const string[]
*/
const NUMERIC_TYPES = [
'tinyint',
'smallint',
'mediumint',
'int',
'integer',
'bigint',
'real',
'double',
'float',
'decimal',
'numeric',
];
/**
* The parsed YAML with a database description
*
* @var array
*/
protected $data;
/**
* Creates a new Parser object
*
* @param string $yasql A string following YAML Ain't SQL specifications
* @param string $name Overwrite database's name
*
* @throws \InvalidArgumentException $yasql is not a mapping
* @throws \RuntimeException Missing Database name
* @throws \DomainException Unsupported source
* @throws \DomainException Unknown index
* @throws \LogicException Missing composite identifiers
* @throws \LogicException Duplicated composite for single column key
* @throws \LengthException Missing column definition
* @throws \RuntimeException Syntax error in Foreign Key
* @throws \LogicException Multiple AUTO_INCREMENT indexes
* @throws \LengthException Column is empty
* @throws \LogicException Multiple PRIMARY KEY indexes
*/
public function __construct(string $yasql, string $name = null)
{
$data = Yaml::parse($yasql);
if ($name !== null) {
$data['database']['name'] = $name;
}
if (!is_array($data)) {
throw new \InvalidArgumentException('YASQL must be a mapping');
}
if (!isset($data['database']['name'])) {
throw new \RuntimeException('Database needs a name');
}
/*
* Define quotation marks
*/
$source = $data['database']['source'] ?? 'MySQL';
switch ($source) {
case 'MySQL':
$quotes = ['`', '`'];
$quotes_escaped = ['``', '``'];
break;
default:
throw new \DomainException('Unsupported source');
break;
}
/*
* Define identifier patterns
*/
$unquoted = '(' . self::IDENTIFIER_PATTERNS['unquoted'] . '+)';
$quoted = $quotes[0]
. '((?:(?![' . implode('', $quotes) . '])'
. self::IDENTIFIER_PATTERNS['quoted']
. '|' . $quotes_escaped[0] . '|' . $quotes_escaped[1] . ')+)'
. $quotes[1];
/*
* Define Foreign Key pattern
*/
$pattern = "/-> ($unquoted *\. *$unquoted|$quoted *\. *$unquoted|$unquoted *\. *$quoted|$quoted *\. *$quoted)( |$)/u";
/*
* Expand composite
*/
$indexes = [];
$id_keys = self::INDEX_KEYWORDS;
foreach ($data['composite'] ?? [] as $composite) {
$result = self::extractKeyword(
$composite,
'^((' . implode('|', array_keys($id_keys)) . ')( KEY|))',
$type
);
if ($result !== false) {
$key = $type[2][0];
} else {
$key = explode(' ', $composite)[0];
throw new \DomainException("Unknown index '$key'");
}
if (preg_match_all(
"/($quoted|$unquoted)/u",
$result,
$matches,
PREG_SET_ORDER
)) {
$identifiers = [];
foreach ($matches as $match) {
$match = array_filter($match);
$identifiers[] = array_pop($match);
}
} else {
$message = "Missing identifiers in composite '$composite'";
throw new \LogicException($message);
}
$table = array_shift($identifiers);
if ($id_keys[$key] === 'single' && isset($indexes[$table][$key])) {
$message = 'Duplicated composite for single column key on table'
. " `$table`";
throw new \LogicException($message);
}
if ($id_keys[$key] === 'multiple') {
$indexes[$table][$key][] = $identifiers;
} else {
$indexes[$table][$key] = $identifiers;
}
}
/*
* Prepare variables
*/
$quote_map = array_combine($quotes, $quotes_escaped);
$tables = $data['tables'] ?? [];
$tables_new = [];
$definitions = $data['definitions'] ?? [];
$auto_increment = [];
$foreigns = [];
/*
* Loop through each column
*/
foreach ($tables as $table => $columns) {
$table = self::escapeQuotes($table, $quote_map);
$primary_key = [];
foreach ($columns as $column => $query) {
$column = self::escapeQuotes($column, $quote_map);
/*
* Pre validation
*/
$query = trim($query);
if (strlen($query) === 0) {
$message = "Missing column definition in `$table`.`$column`";
throw new \LengthException($message);
}
/*
* Expand definitions
*/
if (!empty($definitions)) {
while ($tokens = explode(' ', $query)) {
if (array_key_exists($tokens[0], $definitions)) {
$tokens[0] = $definitions[$tokens[0]];
$query = implode(' ', $tokens);
} else {
break;
}
}
}
/*
* Extract Foreign Key
*/
$fk = strpos($query, '->');
if ($fk !== false) {
preg_match($pattern, substr($query, $fk), $matches);
if (empty($matches)) {
$message = 'Syntax error in Foreign Key on column '
. "`$table`.`$column`";
throw new \RuntimeException($message);
}
$len = strlen($matches[0]);
$query = trim(substr_replace($query, '', $fk, $len));
$matches = array_slice(array_filter($matches), 2, 2);
$foreigns[$table][$column] = $matches;
}
/*
* Extract keywords
*/
$result = self::extractKeyword($query, 'UNSIGNED');
if ($result !== false) {
$query = $result;
$unsigned = true;
} else {
$unsigned = false;
}
$result = self::extractKeyword($query, 'ZEROFILL');
if ($result !== false) {
$query = $result;
$zerofill = ' ZEROFILL';
} else {
$zerofill = '';
}
$result = self::extractKeyword($query, 'AUTO_INCREMENT');
if ($result !== false) {
$query = $result;
if (isset($auto_increment[$table])) {
$message = "Multiple AUTO_INCREMENT on table `$table`";
throw new \LogicException($message);
}
$auto_increment[$table] = $column;
}
$result = self::extractKeyword($query, 'PRIMARY( KEY|)');
if ($result !== false) {
$query = $result;
$primary_key[] = $column;
}
$result = self::extractKeyword($query, 'UNIQUE( KEY|)');
if ($result !== false) {
$query = $result;
$indexes[$table]['UNIQUE'][] = $column;
}
$result = self::extractKeyword($query, '(INDEX|KEY)');
if ($result !== false) {
$query = $result;
$indexes[$table]['INDEX'][] = $column;
}
$result = self::extractKeyword(
$query,
'((DEFAULT|COMMENT|COLUMN_FORMAT|STORAGE|REFERENCES).*)$',
$keywords
);
if ($result !== false) {
$query = $result;
$keywords = $keywords[0][0];
} else {
$keywords = '';
}
/*
* Start to reconstruct
*/
if (self::strContains($query, self::NUMERIC_TYPES)) {
$sign = strpos($query, '+');
if ($sign !== false) {
$query = substr_replace($query, '', $sign, 1);
} elseif ($sign === false || $unsigned) {
$query .= ' UNSIGNED';
}
$query .= $zerofill;
}
$result = self::extractKeyword(
$query,
'(NOT NULL|NULLABLE|NULL)',
$key
);
if ($result !== false) {
$key = ($key[1][0] === 'NULLABLE')
? 'NULL'
: $key[1][0];
$query = $result . ' ' . $key;
} else {
$query .= ' NOT NULL';
}
/*
* Restore keywords
*/
$query .= $keywords;
/*
* Validation
*/
$query = trim($query);
if (strlen($query) === 0) {
$message = "Column `$table`.`$column` is empty";
throw new \LengthException($message);
}
/*
* Store
*/
$tables_new[$table][$column] = $query;
}
/*
* Add PRIMARY KEY
*
* If multiple columns have this attribute, it will be a composite.
* PHP has ordered associative arrays, so it will be in the same
* order as in the YAML. Other languages might produce a composite
* in another order
*/
if (!empty($primary_key)) {
if (isset($indexes[$table]['PRIMARY'])) {
$message = "Multiple PRIMARY KEY on table `$table`";
throw new \LogicException($message);
} else {
$indexes[$table]['PRIMARY'] = $primary_key;
}
}
}
/*
* Update data and store
*/
$data['tables'] = $tables_new;
unset($data['composite'], $data['definitions']);
$data['auto_increment'] = $auto_increment;
$data['indexes'] = $indexes;
$data['foreigns'] = $foreigns;
$this->data = $data;
}
/**
* Escapes quotes in identifiers
*
* @param string $subject Identifier to escape
* @param string[] $quote_map Map of Quote to its SQL escaped form
*
* @return string
*/
protected function escapeQuotes(string $subject, array $quote_map)
{
return str_replace(array_keys($quote_map), $quote_map, $subject);
}
/**
* Extracts a keyword from a string
*
* @param string $haystack String to look for the keyword
* @param string $needle PCRE subpattern with the keyword (insensitive)
* @param string $matches @see \preg_match() $matches (PREG_OFFSET_CAPTURE)
*
* @return false If the keyword was not found
* @return string The string without the keyword
*/
protected static function extractKeyword(
string $haystack,
string $needle,
&$matches = null
) {
$pattern = '/' . (strpos($needle, '^') === 0 ? '' : ' ?') . $needle
. (strrpos($needle, '$') === strlen($needle)-1 ? '' : ' ?') . '/i';
if (preg_match($pattern, $haystack, $matches, PREG_OFFSET_CAPTURE)) {
$m = $matches[0];
$haystack = substr_replace($haystack, ' ', $m[1], strlen($m[0]));
return trim($haystack);
}
return false;
}
/**
* Returns the parsed data
*
* @return array
*/
public function getData()
{
return $this->data;
}
/**
* Tells if a string contains any items in an array (case insensitive)
*
* @author zombat
* @link https://stackoverflow.com/a/2124557
*
* @param string $str A string to be tested
* @param array $arr List of substrings that could be in $str
*
* @return bool
*/
protected static function strContains($str, array $arr)
{
foreach ($arr as $a) {
if (stripos($str, $a) !== false) {
return true;
}
}
return false;
}
}