-
Notifications
You must be signed in to change notification settings - Fork 1
/
ArchieML.php
377 lines (309 loc) · 14.2 KB
/
ArchieML.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
<?php
final class ArchieML
{
const whitespacePattern = '\\x{0000}\\x{0009}\\x{000A}\\x{000B}\\x{000C}\\x{000D}\\x{0020}\\x{00A0}\\x{2000}\\x{2001}\\x{2002}\\x{2003}\\x{2004}\\x{2005}\\x{2006}\\x{2007}\\x{2008}\\x{2009}\\x{200A}\\x{200B}\\x{2028}\\x{2029}\\x{202F}\\x{205F}\\x{3000}\\x{FEFF}';
const slugBlacklist = self::whitespacePattern . '\\x{005B}\\x{005C}\\x{005D}\\x{007B}\\x{007D}\\x{003A}';
const nextLine = '/.*((\r|\n)+)/u';
const startKey = '/^\\s*([^' . self::slugBlacklist . ']+)[ \t\r]*:[ \t\r]*(.*(?:\n|\r|$))/u';
const commandKey = '/^\\s*:[ \t\r]*(endskip|ignore|skip|end).*?(\n|\r|$)/ui';
const arrayElement = '/^\\s*\\*[ \t\r]*(.*(?:\n|\r|$))/u';
const scopePattern = '/^\\s*(\\[|\\{)[ \t\r]*([\+\.]*)[ \t\r]*([^' . self::slugBlacklist . ']*)[ \t\r]*(?:\\]|\\}).*?(\n|\r|$)/u';
private $data;
private $scope;
private $stack;
private $stackScope;
private $bufferScope;
private $bufferKey;
private $bufferString;
private $isSkipping;
public $options = [
'arrayClass' => 'ArrayObject',
'comments' => false
];
public function __construct(array $options = [])
{
$this->options = array_merge($this->options, $options);
}
public static function load($input, $options = [])
{
return (new self($options))->parse($input);
}
public function parse($input)
{
assert('is_string($input)');
$this->initialize();
while ($input) {
// Inside the input stream loop, the `input` string is trimmed down as matches
// are found, and fires a call to the matching parse*() function.
if (preg_match(self::commandKey, $input, $matches)) {
$this->parseCommandKey($input, mb_strtolower($matches[1]));
} else if (!$this->isSkipping && preg_match(self::startKey, $input, $matches) &&
(!$this->stackScope || $this->stackScope['arrayType'] !== 'simple')) {
$this->parseStartKey($matches[1], $matches[2]);
} else if (!$this->isSkipping && preg_match(self::arrayElement, $input, $matches) && $this->stackScope && $this->stackScope['array'] &&
($this->stackScope['arrayType'] !== 'complex' && $this->stackScope['arrayType'] !== 'freeform') &&
strpos($this->stackScope['flags'], '+') === false) {
$this->parseArrayElement($matches[1]);
} else if (!$this->isSkipping && preg_match(self::scopePattern, $input, $matches)) {
$this->parseScope($matches[1], $matches[2], $matches[3]);
} else if (preg_match(self::nextLine, $input, $matches)) {
$this->parseText($input, $matches[0]);
} else {
// End of document reached
$this->parseText($input, $input);
$input = '';
}
if ($matches) {
$input = mb_substr($input, mb_strlen($matches[0]));
}
}
$this->flushBuffer();
return $this->toArray();
}
private function initialize()
{
$this->data = $this->makeArray();
$this->scope = $this->data;
$this->stack = $this->makeArray();
$this->stackScope = null;
$this->bufferScope = null;
$this->bufferKey = null;
$this->bufferString = '';
$this->isSkipping = false;
$this->flushBuffer();
}
private function parseStartKey($key, $restOfLine)
{
// When a new key is encountered, the rest of the line is immediately added as
// its value, by calling `flushBuffer`.
$this->flushBuffer();
$this->incrementArrayElement($key);
if ($this->stackScope && strpos($this->stackScope['flags'], '+') !== false) {
$key = 'value';
}
$this->bufferKey = $key;
$this->bufferString = $restOfLine;
$this->flushBufferInto($key, [ 'replace' => true ]);
}
private function parseArrayElement($value) {
$this->flushBuffer();
$this->stackScope['arrayType'] = $this->stackScope['arrayType'] ?: 'simple';
$this->stackScope['array'][] = '';
$this->bufferKey = $this->stackScope['array'];
$this->bufferString = $value;
$this->flushBufferInto($this->stackScope['array'], [ 'replace' => true ]);
}
private function parseCommandKey(&$input, $command) {
// if isSkipping, don't parse any command unless :endskip
if ($this->isSkipping && !($command === 'endskip' || $command === 'ignore')) {
return $this->flushBuffer();
}
switch ($command) {
case 'end':
// When we get to an end key, save whatever was in the buffer to the last
// active key.
if ($this->bufferKey) {
$this->flushBufferInto($this->bufferKey, [ 'replace' => false ]);
}
return;
case 'ignore':
// When ":ignore" is reached, stop parsing immediately
$input = '';
break;
case 'skip':
$this->isSkipping = true;
break;
case 'endskip':
$this->isSkipping = false;
break;
}
$this->flushBuffer();
}
private function parseScope($scopeType, $flags, $scopeKey) {
// Throughout the parsing, `scope` refers to one of the following:
// * `data`
// * an object - one level within `data` - when we're within a {scope} block
// * an object at the end of an array - which is one level within `data` -
// when we're within an [array] block.
//
// `scope` changes whenever a scope key is encountered. It also changes
// within parseStartKey when we start a new object within an array.
$this->flushBuffer();
if ($scopeKey == '') {
// Move up a level
$lastStackItem = $this->pop($this->stack);
$this->scope = ($lastStackItem ? $lastStackItem['scope'] : $this->data) ?: $this->data;
$this->stackScope = $this->stack->count() ? $this->stack[$this->stack->count() - 1] : null;
} else if ($scopeType === '[' || $scopeType === '{') {
$nesting = false;
$keyScope = $this->data;
// If the flags include ".", drill down into the appropriate scope.
if (strpos($flags, '.') !== false) {
$this->incrementArrayElement($scopeKey, $flags);
$nesting = true;
if ($this->stackScope) {
$keyScope = $this->scope;
}
// Otherwise, make sure we reset to the global scope
} else {
$this->scope = $this->data;
$this->stack = $this->makeArray();
}
// Within freeforms, the `type` of nested objects and arrays is taken
// verbatim from the `keyScope`.
if ($this->stackScope && strpos($this->stackScope['flags'], '+') !== false) {
$parsedScopeKey = $scopeKey;
// Outside of freeforms, dot-notation interpreted as nested data.
} else {
$keyBits = explode('.', $scopeKey);
for ($i = 0; $i < count($keyBits) - 1; $i++) {
$keyScope = $keyScope[$keyBits[$i]] = isset($keyScope[$keyBits[$i]]) ? $keyScope[$keyBits[$i]] : $this->makeArray();
}
$parsedScopeKey = $keyBits[count($keyBits) - 1];
}
// Content of nested scopes within a freeform should be stored under "value."
if ($this->stackScope && strpos($this->stackScope['flags'], '+') !== false && strpos($flags, '.') !== false) {
if ($scopeType === '[') {
$parsedScopeKey = 'value';
} else if ($scopeType === '{') {
$this->scope = $this->scope['value'] = $this->makeArray();
}
}
$stackScopeItem = $this->makeArray([
'array' => null,
'arrayType' => null,
'arrayFirstKey' => null,
'flags' => $flags,
'scope' => $this->scope
]);
if ($scopeType === '[') {
$stackScopeItem['array'] = $keyScope[$parsedScopeKey] = $this->makeArray();
if (strpos($flags, '+') !== false) {
$stackScopeItem['arrayType'] = 'freeform';
}
if ($nesting) {
$this->stack[] = $stackScopeItem;
} else {
$this->stack = $this->makeArray();
$this->stack[] = $stackScopeItem;
}
$this->stackScope = $this->stack[$this->stack->count() - 1];
} else if ($scopeType === '{') {
if ($nesting) {
$this->stack[] = $stackScopeItem;
} else {
// TODO: not sure about this typeof
$this->scope = $keyScope[$parsedScopeKey] = (isset($keyScope[$parsedScopeKey]) && $keyScope[$parsedScopeKey] instanceof $this->options['arrayClass']) ? $keyScope[$parsedScopeKey] : $this->makeArray();
$this->stack = $this->makeArray();
$this->stack[] = $stackScopeItem;
}
$this->stackScope = $this->stack[$this->stack->count() - 1];
}
}
}
private function parseText($input, $text) {
if ($this->stackScope && strpos($this->stackScope['flags'], '+') !== false && preg_match('/[^\n\r\s]/', $text)) {
$this->stackScope['array'][] = $this->makeArray(['type' => 'text', 'value' => trim($text) /* preg_replace('/(^\s*)|(\s*$)/g', $text, '') */ ]);
} else {
$this->bufferString .= substr($input, 0, mb_strlen($text));
}
}
private function incrementArrayElement($key) {
// Special handling for arrays. If this is the start of the array, remember
// which key was encountered first. If this is a duplicate encounter of
// that key, start a new object.
if ($this->stackScope && $this->stackScope['array']) {
// If we're within a simple array, ignore
$this->stackScope['arrayType'] = $this->stackScope['arrayType'] ?: 'complex';
if ($this->stackScope['arrayType'] === 'simple') return;
// arrayFirstKey may be either another key, or null
if ($this->stackScope['arrayFirstKey'] === null || $this->stackScope['arrayFirstKey'] === $key) {
$this->stackScope['array'][] = $this->scope = $this->makeArray();
}
if (strpos($this->stackScope['flags'], '+') !== false) {
$this->scope['type'] = $key;
} else {
$this->stackScope['arrayFirstKey'] = $this->stackScope['arrayFirstKey'] ?: $key;
}
}
}
private function formatValue($value, $type) {
if ($this->options['comments']) {
$value = preg_replace('/(?:^\\)?\[[^\[\]\n\r]*\](?!\])/mg', '', $value); // remove comments
$value = preg_replace('/\[\[([^\[\]\n\r]*)\]\]/g', '[$1]', $value); // [[]] => []
}
if ($type == 'append') {
// If we're appending to a multi-line string, escape special punctuation
// by using a backslash at the beginning of any line.
// Note we do not do this processing for the first line of any value.
$value = preg_replace('/^(\\s*)\\\\/m', '$1', $value);
}
return $value;
}
private function flushBuffer() {
$result = $this->bufferString . '';
$this->bufferString = '';
$this->bufferKey = null;
return $result;
}
private function flushBufferInto($key, $options = []) {
$existingBufferKey = $this->bufferKey;
$value = $this->flushBuffer();
if ($options['replace']) {
$value = ltrim($this->formatValue($value, 'replace')); // preg_replace('/^\\s*/', $this->formatValue($value, 'replace'), '');
preg_match('/\\s*$/', $value, $matches);
$this->bufferString = $matches[0];
$this->bufferKey = $existingBufferKey;
} else {
$value = $this->formatValue($value, 'append');
}
if ($key instanceof $this->options['arrayClass']) {
// key is an array
if ($options['replace']) {
$key[$key->count() - 1] = '';
}
$key[$key->count() - 1] .= rtrim($value); // preg_replace('/\\s*$/', $value, '');
} else {
$keyBits = explode('.', $key);
$this->bufferScope = $this->scope;
for ($i = 0; $i < count($keyBits) - 1; $i++) {
if (isset($this->bufferScope[$keyBits[$i]]) && is_string($this->bufferScope[$keyBits[$i]])) {
$this->bufferScope[$keyBits[$i]] = $this->makeArray();
}
$this->bufferScope = $this->bufferScope[$keyBits[$i]] = isset($this->bufferScope[$keyBits[$i]]) ? $this->bufferScope[$keyBits[$i]] : $this->makeArray();
}
if ($options['replace']) {
$this->bufferScope[$keyBits[count($keyBits) - 1]] = '';
}
$this->bufferScope[$keyBits[count($keyBits) - 1]] .= rtrim($value); // preg_replace('/\\s*$/', $value, '');
}
}
private function makeArray($input = [])
{
return new $this->options['arrayClass']($input);
}
private function toArray($array = null)
{
$result = [];
if (is_null($array)) {
$array = $this->data;
}
foreach ($array as $key => $value) {
$result[$key] = $value instanceof ArrayObject ? $this->toArray($value) : $value;
}
return $result;
}
private function pop($arrayObject) {
$array = $arrayObject->getArrayCopy();
$lastValue = array_pop($array);
$arrayObject->exchangeArray($array);
return $lastValue;
}
private static function stringResource($string)
{
$handle = fopen('php://memory', 'w+');
fwrite($handle, $string);
rewind($handle);
return $handle;
}
}