-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathToml.php
750 lines (655 loc) · 19.6 KB
/
Toml.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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
<?php
namespace core;
/*
* @Copyright (c) 2013 Leonel Quinteros
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of the nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* PHP parser for TOML language: https://github.com/mojombo/toml
*
* @author Leonel Quinteros https://github.com/leonelquinteros
*
* @version 1.0.0
*
*/
class Toml
{
/**
* Reads string from specified file path and parses it as TOML.
*
* @param (string) File path
*
* @return (array) Toml::parse() result
*/
public static function parseFile($path)
{
if (!is_file($path)) {
throw new \Exception('Invalid file path');
}
$toml = file_get_contents($path);
// Remove BOM if present
$toml = preg_replace('/^' . pack('H*', 'EFBBBF') . '/', '', $toml);
return self::parse($toml);
}
/**
* Parses a TOML string to retrieve a hashed array of data.
*
* @param (string) $toml TOML formatted string
*
* @return (array) Parsed TOML file into array.
*/
public static function parse($toml)
{
$result = new \stdClass();
$pointer = & $result;
// Pre-compile
$toml = self::normalize($toml);
// Split lines
$aToml = explode("\n", $toml);
for ($ln = 0; $ln < count($aToml); $ln++) {
$line = trim($aToml[$ln]);
// Skip commented and empty lines
if (empty($line) || $line[0] == '#') {
continue;
}
// Array of Tables
if (substr($line, 0, 2) == '[[' && substr($line, -2) == ']]') {
// Set pointer at top level.
$pointer = & $result;
$tableName = substr($line, 2, -2);
$aTable = self::parseTableName($tableName);
$last = count($aTable) - 1;
foreach ($aTable as $i => $tableName) {
$tableName = trim($tableName);
if ($tableName == "") {
// Empty table name
throw new \Exception("Empty table keys aren't allowed");
}
// Allow quoted table names
if ($tableName[0] == '"' && substr($tableName, -1) == '"') {
$tableName = json_decode($tableName);
} elseif (!ctype_alnum(str_replace(['-', '_', '.'], '', $tableName))) { // Check for proper keys
// Invalid table name
throw new \Exception("Invalid table name: " . $tableName);
}
// Create array of tables and move pointer forward
if (is_array($pointer) && !isset($pointer[$tableName])) {
$pointer[$tableName] = [];
} elseif (is_object($pointer) && !isset($pointer->$tableName)) {
$pointer->$tableName = [];
}
if (is_array($pointer)) {
$pointer = & $pointer[$tableName];
} else {
$pointer = & $pointer->$tableName;
}
// Handle array of tables
if ($i < $last && is_array($pointer)) {
end($pointer);
$pointer = & $pointer[key($pointer)];
}
}
// Add item to array of tables
$pointer[] = [];
end($pointer);
$pointer = & $pointer[key($pointer)];
}
// Single Tables
elseif ($line[0] == '[' && substr($line, -1) == ']') {
// Set pointer at first level.
$pointer = & $result;
$tableName = substr($line, 1, -1);
$tableName = trim($tableName);
//$aTable = explode('.', $tableName);
$aTable = self::parseTableName($tableName);
$last = count($aTable) - 1;
foreach ($aTable as $i => $tableName) {
if ($tableName == "") {
// Empty table name
throw new \Exception("Empty table keys aren't allowed on line " . $line);
}
// Allow quoted table names
if (($tableName[0] == '"' && substr($tableName, -1) == '"') || ($tableName[0] == "'" && substr($tableName, -1) == "'")) {
$tableName = json_decode($tableName);
} elseif (!ctype_alnum(str_replace(['-', '_', '.'], '', $tableName))) { // Check for proper keys
// Invalid table name
throw new \Exception("Invalid table name: " . $tableName);
}
if (is_array($pointer) && !isset($pointer[$tableName])) {
// Create table
$pointer[$tableName] = new \stdClass();
} elseif (is_object($pointer) && !isset($pointer->$tableName)) {
$pointer->$tableName = new \stdClass();
} elseif ($i == $last) {
// Overwrite key
throw new \Exception('Key overwrite previous keys: ' . $line);
}
// Move pointer forward
if (is_array($pointer)) {
$pointer = & $pointer[$tableName];
} else {
$pointer = & $pointer->$tableName;
}
// Handle array of tables
if (is_array($pointer)) {
end($pointer);
$pointer = & $pointer[key($pointer)];
}
}
}
// Key = Values
elseif (strpos($line, '=')) {
$kv = explode('=', $line, 2);
if (is_object($pointer) && !isset($pointer->{trim($kv[0])})
|| is_array($pointer) && !isset($pointer[trim($kv[0])])
) {
// Multi-line strings
if (substr(trim($kv[1]), 0, 3) == '"""') {
if (strlen(trim($kv[1])) > 3 && substr(trim($kv[1]), -3) != '"""' || strlen(trim($kv[1])) == 3) {
do {
$ln++;
$kv[1] .= "\n" . $aToml[$ln];
} while (strpos($aToml[$ln], '"""') === false);
}
}
// Multi-line literal strings
if (substr(trim($kv[1]), 0, 3) == "'''") {
if (strlen(trim($kv[1])) > 3 && substr(trim($kv[1]), -3) != "'''" || strlen(trim($kv[1])) == 3) {
do {
$ln++;
$kv[1] .= "\n" . $aToml[$ln];
} while (strpos($aToml[$ln], "'''") === false);
}
}
// Set key=value
$key = self::parseKeyValue(trim($kv[0]), trim($kv[1]), $pointer);
} else {
throw new \Exception('Key overwrite previous keys: ' . $line);
}
} elseif ($line[0] == '[' && substr($line, -1) != ']') {
throw new \Exception('Key groups have to be on a line by themselves: ' . $line);
} else {
throw new \Exception('Syntax error on: ' . $line);
}
}
return $result;
}
/**
* Performs text modifications in order to normalize the TOML file for the parser.
* Kind of pre-compiler.
*
* @param (string) $toml TOML string.
*
* @return (string) Normalized TOML string
*/
private static function normalize($toml)
{
// Cleanup EOL chars.
$toml = str_replace(["\r\n", "\n\r"], "\n", $toml);
// Cleanup TABs
$toml = str_replace("\t", " ", $toml);
// Run, char by char.
$normalized = '';
$openString = false;
$openLString = false;
$openMString = false;
$openMLString = false;
$openBrackets = 0;
$openKeygroup = false;
$lineBuffer = '';
$strLen = strlen($toml);
for ($i = 0; $i < $strLen; $i++) {
$keep = true;
if ($toml[$i] == '[' && !$openString && !$openLString && !$openMString && !$openMLString) {
// Keygroup or array definition start outside a string
$openBrackets++;
// Keygroup
if ($openBrackets == 1 && trim($lineBuffer) == '') {
$openKeygroup = true;
}
} elseif ($toml[$i] == ']' && !$openString && !$openLString && !$openMString && !$openMLString) {
// Keygroup or array definition end outside a string
if ($openBrackets > 0) {
$openBrackets--;
if ($openKeygroup) {
$openKeygroup = false;
}
} else {
throw new \Exception("Unexpected ']' on: " . $lineBuffer);
}
} elseif ($openBrackets > 0 && $toml[$i] == "\n") {
// Multi-line keygroup definition is not alowed.
if ($openKeygroup) {
throw new \Exception('Multi-line keygroup definition is not allowed on: ' . $lineBuffer);
}
// EOLs inside array definition. We don't want them.
$keep = false;
} elseif (($openString || $openLString) && $toml[$i] == "\n") {
// EOLs inside string should throw error.
throw new \Exception("Multi-line string not allowed on: " . $lineBuffer);
} elseif ($toml[$i] == '"' && $toml[$i - 1] != "\\" && !$openLString && !$openMLString) { // String handling, allow escaped quotes.
// Check multi-line strings
if (substr($toml, $i, 3) == '"""') {
// Include the token inmediately.
$i += 2;
$normalized .= '"""';
$lineBuffer .= '"""';
;
$keep = false;
$openMString = !$openMString;
} elseif (!$openMString) { // Simple strings
$openString = !$openString;
}
} elseif ($toml[$i] == "'" && !$openString && !$openMString) { // Literal string handling.
// Check multi-line strings
if (substr($toml, $i, 3) == "'''") {
// Include the token inmediately.
$i += 2;
$normalized .= "'''";
$lineBuffer .= "'''";
$keep = false;
$openMLString = !$openMLString;
} elseif (!$openMLString) { // Simple strings
$openLString = !$openLString;
}
} elseif ($toml[$i] == "\\" && $toml[$i-1] != "\\" && !in_array($toml[$i+1], ['b', 't', 'n', 'f', 'r', 'u', 'U', '"', "\\", ' '])) {
// Reserved special characters inside strings should produce error
if ($openString) {
throw new \Exception('Reserved special characters inside strings are not allowed: ' . $toml[$i] . $toml[$i+1]);
}
// Cleanup escaped new lines and whitespaces from multi-line strings
if ($openMString) {
while ($toml[$i+1] == "\n" || $toml[$i+1] == " ") {
$i++;
$keep = false;
}
}
} elseif ($toml[$i] == '#' && !$openString && !$openKeygroup) {
// Remove comments only at the end of the line. Doesn't catch comments inside array definition.
while (isset($toml[$i]) && $toml[$i] != "\n") {
$i++;
}
// Last char we know it's EOL.
$keep = ($openBrackets == 0);
}
// Raw Lines
if (isset($toml[$i])) {
$lineBuffer .= $toml[$i];
if ($toml[$i] == "\n") {
$lineBuffer = '';
}
if ($keep) {
$normalized .= $toml[$i];
}
}
}
// Something went wrong.
if ($openBrackets) {
throw new \Exception('Syntax error found on TOML document. Missing closing bracket.');
}
if ($openString) {
throw new \Exception('Syntax error found on TOML document. Missing closing string delimiter.');
}
if ($openMString) {
throw new \Exception('Syntax error found on TOML document. Missing closing multi-line string delimiter.');
}
if ($openLString) {
throw new \Exception('Syntax error found on TOML document. Missing closing literal string delimiter.');
}
if ($openMLString) {
throw new \Exception('Syntax error found on TOML document. Missing closing multi-line literal string delimiter.');
}
if ($openKeygroup) {
throw new \Exception('Syntax error found on TOML document. Missing closing key group delimiter.');
}
return $normalized;
}
/**
* Parses TOML table names and returns the hierarchy array of table names.
*
* @param (string) $name
*
* @return (array) Table names
*/
private static function parseTableName($name)
{
// Init buffer
$buffer = '';
$strOpen = false;
$names = [];
$strLen = strlen($name);
for ($i = 0; $i < $strLen; $i++) {
if ($name[$i] == '"') {
// Toggle strings
if (!$strOpen || ($strOpen && $name[$i - 1] != "\\")) {
$strOpen = !$strOpen;
}
} elseif ($name[$i] == '.' && !$strOpen) {
// Save and cleanup buffer. Continue.
$names[] = $buffer;
$buffer = '';
continue;
}
// Store char
$buffer .= $name[$i];
}
// Save last buffer
if ($buffer != '') {
$names[] = $buffer;
}
return $names;
}
/**
* Parses TOML value and returns it to be assigned on the hashed array
*
* @param (string) $val
*
* @return (mixed) Parsed value.
*/
private static function parseValue($val)
{
$parsedVal = null;
// Cleanup
$val = trim($val);
if ($val === '') {
throw new \Exception('Empty value not allowed');
}
// Boolean
if ($val == 'true' || $val == 'false') {
$parsedVal = ($val == 'true');
}
// Literal multi-line string
elseif (substr($val, 0, 3) == "'''" && substr($val, -3) == "'''") {
$parsedVal = substr($val, 3, -3);
// Trim first newline on multi-line string definition
if ($parsedVal[0] == "\n") {
$parsedVal = substr($parsedVal, 1);
}
}
// Literal string
elseif ($val[0] == "'" && substr($val, -1) == "'") {
// No newlines allowed
if (strpos($val, "\n") !== false) {
throw new \Exception('New lines not allowed on single line string literals.');
}
$parsedVal = substr($val, 1, -1);
}
// Multi-line string
elseif (substr($val, 0, 3) == '"""' && substr($val, -3) == '"""') {
$parsedVal = substr($val, 3, -3);
// Trim first newline on multi-line string definition
if ($parsedVal[0] == "\n") {
$parsedVal = substr($parsedVal, 1);
}
// Use json_decode to finally parse the string.
$parsedVal = json_decode('"' . str_replace("\n", '\n', $parsedVal) . '"');
}
// String
elseif ($val[0] == '"' && substr($val, -1) == '"') {
// TOML's specification says it's the same as for JSON format... so
$parsedVal = json_decode($val);
}
// Numbers
elseif (is_numeric(str_replace('_', '', $val))) {
$val = str_replace('_', '', $val);
$intVal = filter_var($val, FILTER_VALIDATE_INT);
if ($intVal !== false) {
$parsedVal = $intVal;
} else {
$parsedVal = (float) $val;
}
}
// Datetime. Parsed to UNIX time value.
elseif (self::isISODate($val)) {
$parsedVal = new \DateTime($val);
}
// Single line array (normalized)
elseif ($val[0] == '[' && substr($val, -1) == ']') {
$parsedVal = self::parseArray($val);
}
// Inline table (normalized)
elseif ($val[0] == '{' && substr($val, -1) == '}') {
$parsedVal = self::parseInlineTable($val);
} else {
throw new \Exception('Unknown value type: ' . $val);
}
return $parsedVal;
}
/**
* Recursion function to parse all array values through self::parseValue()
*
* @param (array) $array
*
* @return (array) Parsed array.
*/
private static function parseArray($val)
{
$result = [];
$openBrackets = 0;
$openString = false;
$openLString = false;
$buffer = '';
$strLen = strlen($val);
for ($i = 0; $i < $strLen; $i++) {
if ($val[$i] == '[' && !$openString && !$openLString) {
$openBrackets++;
if ($openBrackets == 1) {
// Skip first and last brackets.
continue;
}
} elseif ($val[$i] == ']' && !$openString && !$openLString) {
$openBrackets--;
if ($openBrackets == 0) {
// Allow terminating commas before the closing bracket
if (trim($buffer) != '') {
$result[] = self::parseValue(trim($buffer));
}
if (!self::checkDataType($result)) {
throw new \Exception('Data types cannot be mixed in an array: ' . $buffer);
}
// Skip first and last brackets. We're finish.
return $result;
}
} elseif ($val[$i] == '"' && $val[$i - 1] != "\\" && !$openLString) {
$openString = !$openString;
} elseif ($val[$i] == "'" && !$openString) {
$openLString = !$openLString;
}
if ($val[$i] == ',' && !$openString && !$openLString && $openBrackets == 1) {
$result[] = self::parseValue(trim($buffer));
if (!self::checkDataType($result)) {
throw new \Exception('Data types cannot be mixed in an array: ' . $buffer);
}
$buffer = '';
} else {
$buffer .= $val[$i];
}
}
// If we're here, something went wrong.
throw new \Exception('Wrong array definition: ' . $val);
}
/**
* Parse inline tables into common table array
*/
private static function parseInlineTable($val)
{
// Check valid inline table
if ($val[0] == '{' && substr($val, -1) == '}') {
$val = substr($val, 1, -1);
} else {
throw new \Exception('Invalid inline table definition: ' . $val);
}
$result = new \stdClass();
$openString = false;
$openLString = false;
$buffer = '';
$strLen = strlen($val);
for ($i = 0; $i < $strLen; $i++) {
// Handle strings
if ($val[$i] == '"' && $val[$i - 1] != "\\") {
$openString = !$openString;
} elseif ($val[$i] == "'") {
$openLString = !$openLString;
}
if ($val[$i] == ',' && !$openString && !$openLString) {
// Parse buffer
$kv = explode('=', $buffer, 2);
$result->{trim($kv[0])} = self::parseValue(trim($kv[1]));
// Clear buffer
$buffer = '';
} else {
$buffer .= $val[$i];
}
}
// Parse last buffer
$kv = explode('=', $buffer, 2);
$result->{trim($kv[0])} = self::parseValue(trim($kv[1]));
return $result;
}
/**
* Function that takes a key expression and the current pointer to position in the right hierarchy.
* Then it sets the corresponding value on that position.
*
* @param (string) $key
* @param (&) $pointer
*/
private static function parseKeyValue($key, $val, & $pointer)
{
// Flags
$openQuote = false;
$openDoubleQuote = false;
// Buffer
$buff = '';
// Parse
for ($i = 0; $i < strlen($key); $i++) {
// Handle quoting
if ($key[$i] == '"') {
if (!$openQuote) {
if ($openDoubleQuote) {
$openDoubleQuote = false;
} else {
$openDoubleQuote = true;
}
continue;
}
}
if ($key[$i] == "'") {
if (!$openDoubleQuote) {
if ($openQuote) {
$openQuote = false;
} else {
$openQuote = true;
}
continue;
}
}
// Handle dotted keys
if ($key[$i] == "." && !$openQuote && !$openDoubleQuote) {
if (is_array($pointer)) {
if (!isset($pointer[$buff])) {
$pointer[$buff] = new \stdClass();
}
$pointer = & $pointer[$buff];
} else {
if (!isset($pointer->{$buff})) {
$pointer->{$buff} = new \stdClass();
}
$pointer = & $pointer->{$buff};
}
// Cleanup buffer
$buff = '';
continue;
}
$buff .= $key[$i];
}
if (is_array($pointer)) {
$pointer[$buff] = self::parseValue($val);
} else {
$pointer->{$buff} = self::parseValue($val);
}
return $buff;
}
/**
* Function that checks the data type of the first and last elements of an array,
* and returns false if they don't match
*
* @param (array) $array
*
* @return boolean
*/
private static function checkDataType($array)
{
if (count($array) <= 1) {
return true;
}
$last = count($array) - 1;
$type = self::getCustomDataType($array[$last]);
if ($type != self::getCustomDataType($array[0])) {
return false;
} else {
return true;
}
}
/**
* Returns the data type of a variable
*
* @param (mixed) $val
* @return (string) Data type of value
*/
private static function getCustomDataType($val)
{
if (!is_array($val)) {
$type = "date";
} else {
$type = gettype($val);
}
return $type;
}
/**
* Return whether the given value is a valid ISODate
*
* @param (string) $val
* @return boolean
*/
public static function isISODate($val)
{
return false;
if (!is_string($val)) {
return false;
}
// Use DateTime support to check for valid dates.
try {
$date = new \DateTime($val);
} catch (Exception $e) {
return false;
}
return true;
}
}