forked from thunderer/Shortcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegularParser.php
More file actions
403 lines (348 loc) · 13.4 KB
/
RegularParser.php
File metadata and controls
403 lines (348 loc) · 13.4 KB
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
<?php
namespace Thunder\Shortcode\Parser;
use Thunder\Shortcode\Shortcode\ParsedShortcode;
use Thunder\Shortcode\Shortcode\Shortcode;
use Thunder\Shortcode\Syntax\CommonSyntax;
use Thunder\Shortcode\Syntax\SyntaxInterface;
use Thunder\Shortcode\Utility\RegexBuilderUtility;
/**
* @author Tomasz Kowalczyk <tomasz@kowalczyk.cc>
*/
final class RegularParser implements ParserInterface
{
/** @var non-empty-string */
private $lexerRegex;
/** @var non-empty-string */
private $nameRegex;
/** @psalm-var list<array{0:int,1:string,2:int}> */
private $tokens = array();
/** @var int */
private $tokensCount = 0;
/** @var int */
private $position = 0;
/** @var int[] */
private $backtracks = array();
/** @var int */
private $lastBacktrack = 0;
const TOKEN_OPEN = 1;
const TOKEN_CLOSE = 2;
const TOKEN_MARKER = 3;
const TOKEN_SEPARATOR = 4;
const TOKEN_DELIMITER = 5;
const TOKEN_STRING = 6;
const TOKEN_WS = 7;
/** @param SyntaxInterface|null $syntax */
public function __construct($syntax = null)
{
if(null !== $syntax && false === $syntax instanceof SyntaxInterface) {
throw new \LogicException('Parameter $syntax must be an instance of SyntaxInterface.');
}
$this->lexerRegex = $this->prepareLexer($syntax ?: new CommonSyntax());
$this->nameRegex = '~^'.RegexBuilderUtility::buildNameRegex().'$~us';
}
/**
* @param string $text
*
* @return ParsedShortcode[]
*/
public function parse($text)
{
$nestingLevel = ini_set('xdebug.max_nesting_level', '-1');
$this->tokens = $this->tokenize($text);
$this->backtracks = array();
$this->lastBacktrack = 0;
$this->position = 0;
$this->tokensCount = \count($this->tokens);
$shortcodes = array();
while($this->position < $this->tokensCount) {
while($this->position < $this->tokensCount && false === $this->lookahead(self::TOKEN_OPEN)) {
$this->position++;
}
$names = array();
$this->beginBacktrack();
$matches = $this->shortcode($names);
if(false === $matches) {
$this->backtrack();
$this->match(null, true);
continue;
}
if(\is_array($matches)) {
foreach($matches as $shortcode) {
$shortcodes[] = $shortcode;
}
}
}
ini_set('xdebug.max_nesting_level', $nestingLevel);
return $shortcodes;
}
/**
* @param string $name
* @psalm-param array<string,string|null> $parameters
* @param string|null $bbCode
* @param int $offset
* @param string|null $content
* @param string $text
*
* @return ParsedShortcode
*/
private function getObject($name, $parameters, $bbCode, $offset, $content, $text)
{
return new ParsedShortcode(new Shortcode($name, $parameters, $content, $bbCode), $text, $offset);
}
/* --- RULES ----------------------------------------------------------- */
/**
* @param string[] $names
* @psalm-param list<string> $names
* FIXME: investigate the reason Psalm complains about references
* @psalm-suppress ReferenceConstraintViolation
*
* @return ParsedShortcode[]|string|false
*/
private function shortcode(array &$names)
{
if(!$this->match(self::TOKEN_OPEN, false)) { return false; }
$offset = $this->tokens[$this->position - 1][2];
$this->match(self::TOKEN_WS, false);
if('' === $name = $this->match(self::TOKEN_STRING, false)) { return false; }
if($this->lookahead(self::TOKEN_STRING)) { return false; }
if(1 !== preg_match($this->nameRegex, $name, $matches)) { return false; }
$this->match(self::TOKEN_WS, false);
// bbCode
$bbCode = $this->match(self::TOKEN_SEPARATOR, true) ? $this->value() : null;
if(false === $bbCode) { return false; }
// parameters
if(false === ($parameters = $this->parameters())) { return false; }
// self-closing
if($this->match(self::TOKEN_MARKER, true)) {
if(!$this->match(self::TOKEN_CLOSE, false)) { return false; }
return array($this->getObject($name, $parameters, $bbCode, $offset, null, $this->getBacktrack()));
}
// just-closed or with-content
if(!$this->match(self::TOKEN_CLOSE, false)) { return false; }
$this->beginBacktrack();
$names[] = $name;
// begin inlined content()
$content = '';
$shortcodes = array();
$closingName = null;
while($this->position < $this->tokensCount) {
while($this->position < $this->tokensCount && false === $this->lookahead(self::TOKEN_OPEN)) {
$content .= $this->match(null, true);
}
$this->beginBacktrack();
$contentMatchedShortcodes = $this->shortcode($names);
if(\is_string($contentMatchedShortcodes)) {
$closingName = $contentMatchedShortcodes;
break;
}
if(\is_array($contentMatchedShortcodes)) {
foreach($contentMatchedShortcodes as $matchedShortcode) {
$shortcodes[] = $matchedShortcode;
}
continue;
}
$this->backtrack();
$this->beginBacktrack();
if(false !== ($closingName = $this->close($names))) {
$this->backtrack();
$shortcodes = array();
break;
}
$closingName = null;
$this->backtrack();
$content .= $this->match(null, false);
}
$content = $this->position < $this->tokensCount ? $content : false;
// end inlined content()
if(null !== $closingName && $closingName !== $name) {
array_pop($names);
array_pop($this->backtracks);
array_pop($this->backtracks);
return $closingName;
}
if(false === $content || $closingName !== $name) {
$this->backtrack(false);
$text = $this->backtrack(false);
array_pop($names);
return array_merge(array($this->getObject($name, $parameters, $bbCode, $offset, null, $text)), $shortcodes);
}
$content = $this->getBacktrack();
/** @psalm-suppress RiskyTruthyFalsyComparison */
if(!$this->close($names)) { return false; }
array_pop($names);
return array($this->getObject($name, $parameters, $bbCode, $offset, $content, $this->getBacktrack()));
}
/**
* @param string[] $names
*
* @return string|false
*/
private function close(array &$names)
{
if(!$this->match(self::TOKEN_OPEN, true)) { return false; }
if(!$this->match(self::TOKEN_MARKER, true)) { return false; }
if(!$closingName = $this->match(self::TOKEN_STRING, true)) { return false; }
if(!$this->match(self::TOKEN_CLOSE, false)) { return false; }
return \in_array($closingName, $names, true) ? $closingName : false;
}
/** @psalm-return array<string,string|null>|false */
private function parameters()
{
$parameters = array();
while(true) {
$this->match(self::TOKEN_WS, false);
if($this->lookahead(self::TOKEN_MARKER) || $this->lookahead(self::TOKEN_CLOSE)) { break; }
if(!$name = $this->match(self::TOKEN_STRING, true)) { return false; }
if(!$this->match(self::TOKEN_SEPARATOR, true)) { $parameters[$name] = null; continue; }
if(false === ($value = $this->value())) { return false; }
$this->match(self::TOKEN_WS, false);
$parameters[$name] = $value;
}
return $parameters;
}
/** @return false|string */
private function value()
{
$value = '';
if($this->match(self::TOKEN_DELIMITER, false)) {
while($this->position < $this->tokensCount && false === $this->lookahead(self::TOKEN_DELIMITER)) {
$value .= $this->match(null, false);
}
return $this->match(self::TOKEN_DELIMITER, false) ? $value : false;
}
if('' !== $tmp = $this->match(self::TOKEN_STRING, false)) {
$value .= $tmp;
while('' !== $tmp = $this->match(self::TOKEN_STRING, false)) {
$value .= $tmp;
}
return $value;
}
return false;
}
/* --- PARSER ---------------------------------------------------------- */
/** @return void */
private function beginBacktrack()
{
$this->backtracks[] = $this->position;
$this->lastBacktrack = $this->position;
}
/** @return string */
private function getBacktrack()
{
$position = array_pop($this->backtracks);
$backtrack = '';
for($i = $position; $i < $this->position; $i++) {
$backtrack .= $this->tokens[$i][1];
}
return $backtrack;
}
/**
* @param bool $modifyPosition
*
* @return string
*/
private function backtrack($modifyPosition = true)
{
$position = array_pop($this->backtracks);
if($modifyPosition) {
$this->position = $position;
}
$backtrack = '';
for($i = $position; $i < $this->lastBacktrack; $i++) {
$backtrack .= $this->tokens[$i][1];
}
$this->lastBacktrack = $position;
return $backtrack;
}
/**
* @param int $type
*
* @return bool
*/
private function lookahead($type)
{
return $this->position < $this->tokensCount && $this->tokens[$this->position][0] === $type;
}
/**
* @param int|null $type
* @param bool $ws
*
* @return string
*/
private function match($type, $ws)
{
if($this->position >= $this->tokensCount) {
return '';
}
$token = $this->tokens[$this->position];
/** @psalm-suppress RiskyTruthyFalsyComparison */
if(!empty($type) && $token[0] !== $type) {
return '';
}
$this->position++;
if($ws && $this->position < $this->tokensCount && $this->tokens[$this->position][0] === self::TOKEN_WS) {
$this->position++;
}
return $token[1];
}
/* --- LEXER ----------------------------------------------------------- */
/**
* @param string $text
*
* @psalm-return list<array{0:int,1:string,2:int}>
*/
private function tokenize($text)
{
$count = preg_match_all($this->lexerRegex, $text, $matches, PREG_SET_ORDER);
if(false === $count || preg_last_error() !== PREG_NO_ERROR) {
throw new \RuntimeException(sprintf('PCRE failure `%s`.', preg_last_error()));
}
$tokens = array();
$position = 0;
foreach($matches as $match) {
switch(true) {
case array_key_exists('close', $match): { $token = $match['close']; $type = self::TOKEN_CLOSE; break; }
case array_key_exists('open', $match): { $token = $match['open']; $type = self::TOKEN_OPEN; break; }
case array_key_exists('separator', $match): { $token = $match['separator']; $type = self::TOKEN_SEPARATOR; break; }
case array_key_exists('delimiter', $match): { $token = $match['delimiter']; $type = self::TOKEN_DELIMITER; break; }
case array_key_exists('marker', $match): { $token = $match['marker']; $type = self::TOKEN_MARKER; break; }
case array_key_exists('ws', $match): { $token = $match['ws']; $type = self::TOKEN_WS; break; }
case array_key_exists('string', $match): { $token = $match['string']; $type = self::TOKEN_STRING; break; }
default: { throw new \RuntimeException('Invalid token.'); }
}
$tokens[] = array($type, $token, $position);
$position += mb_strlen($token, 'utf-8');
}
return $tokens;
}
/** @return non-empty-string */
private function prepareLexer(SyntaxInterface $syntax)
{
// FIXME: for some reason Psalm does not understand the `@psalm-var callable() $var` annotation
/** @psalm-suppress MissingClosureParamType, MissingClosureReturnType */
$group = function($text, $group) {
return '(?<'.(string)$group.'>'.preg_replace('/(.)/us', '\\\\$0', (string)$text).')';
};
/** @psalm-suppress MissingClosureParamType, MissingClosureReturnType */
$quote = function($text) {
return preg_replace('/(.)/us', '\\\\$0', (string)$text);
};
$rules = array(
'(?<string>\\\\.|(?:(?!'.implode('|', array(
$quote($syntax->getOpeningTag()),
$quote($syntax->getClosingTag()),
$quote($syntax->getClosingTagMarker()),
$quote($syntax->getParameterValueSeparator()),
$quote($syntax->getParameterValueDelimiter()),
'\s+',
)).').)+)',
'(?<ws>\s+)',
$group($syntax->getClosingTagMarker(), 'marker'),
$group($syntax->getParameterValueDelimiter(), 'delimiter'),
$group($syntax->getParameterValueSeparator(), 'separator'),
$group($syntax->getOpeningTag(), 'open'),
$group($syntax->getClosingTag(), 'close'),
);
return '~('.implode('|', $rules).')~us';
}
}