diff --git a/README.md b/README.md index 121eaca..52ba68b 100644 --- a/README.md +++ b/README.md @@ -203,7 +203,7 @@ This section discusses available shortcode parsers. Regardless of the parser tha There are four included parsers in this library: - `RegularParser` is the most powerful and correct parser available in this library. It contains the actual parser designed to handle all the issues with shortcodes like proper nesting or detecting invalid shortcode syntax. It is slightly slower than regex-based parser described below, -- `HybridParser` produces exactly the same result as `RegularParser`, including proper nesting and invalid syntax detection, but it lexes every tag in a single regular expression pass and resolves nesting with a flat stack instead of a recursive token parser. This makes it several times faster than `RegularParser` and much lighter on memory, since it never builds a token array for the whole input. It is a good choice when you want `RegularParser`'s correctness without its cost, +- `StackParser` produces exactly the same result as `RegularParser`, including proper nesting and invalid syntax detection, but it lexes every tag in a single regular expression pass and resolves nesting with a flat stack instead of a recursive token parser. This makes it several times faster than `RegularParser` and much lighter on memory, since it never builds a token array for the whole input. It is a good choice when you want `RegularParser`'s correctness without its cost, - `RegexParser` uses a handcrafted regular expression dedicated to handle shortcode syntax as much as regex engine allows. It is fastest among the parsers included in this library, but it can't handle nesting properly, which means that nested shortcodes with the same name are also considered overlapping - (assume that shortcode `[c]` returns its content) string `[c]x[c]y[/c]z[/c]` will be interpreted as `xyz[/c]` (first closing tag was matched to first opening tag). This can be solved by aliasing handler name, because for example `[c]x[d]y[/d]z[/c]` will be processed correctly, - `WordpressParser` contains code copied from the latest currently available WordPress (4.3.1). It is also a regex-based parser, but the included regular expression is quite weak, it for example won't support BBCode syntax (`[name="param" /]`). This parser by default supports the shortcode name rule, but can break it when created with one of the named constructors (`createFromHandlers()` or `createFromNames()`) that change its behavior to catch only configured names. All of it is intentional to keep the compatibility with what WordPress is capable of if you need that compatibility. diff --git a/mago.toml b/mago.toml index 201f4a7..54ce275 100644 --- a/mago.toml +++ b/mago.toml @@ -9,14 +9,14 @@ minimum-fail-level = "note" [linter.rules] array-style = { style = "long" } -cyclomatic-complexity = { exclude = ["src/Parser/HybridParser.php", "src/Parser/RegexParser.php", "src/Parser/RegularParser.php", "src/Parser/WordpressParser.php", "src/Processor/Processor.php"] } -halstead = { exclude = ["src/Parser/HybridParser.php", "src/Parser/RegularParser.php", "src/Processor/Processor.php", "src/Utility/RegexBuilderUtility.php"] } +cyclomatic-complexity = { exclude = ["src/Parser/StackParser.php", "src/Parser/RegexParser.php", "src/Parser/RegularParser.php", "src/Parser/WordpressParser.php", "src/Processor/Processor.php"] } +halstead = { exclude = ["src/Parser/StackParser.php", "src/Parser/RegularParser.php", "src/Processor/Processor.php", "src/Utility/RegexBuilderUtility.php"] } literal-named-argument = { enabled = false } -no-else-clause = { exclude = ["src/Parser/HybridParser.php", "src/Parser/WordpressParser.php"] } +no-else-clause = { exclude = ["src/Parser/StackParser.php", "src/Parser/WordpressParser.php"] } no-empty = { exclude = ["src/Handler/DeclareHandler.php", "src/HandlerContainer/HandlerContainer.php", "src/Parser/RegularParser.php", "src/Parser/WordpressParser.php", "src/Serializer/TextSerializer.php"] } -no-isset = { exclude = ["src/Parser/HybridParser.php", "src/Parser/RegexParser.php", "src/Parser/WordpressParser.php"] } +no-isset = { exclude = ["src/Parser/StackParser.php", "src/Parser/RegexParser.php", "src/Parser/WordpressParser.php"] } no-redundant-block = { exclude = ["src/Parser/RegularParser.php"] } -no-shorthand-ternary = { exclude = ["src/Parser/HybridParser.php", "src/Parser/RegexParser.php", "src/Parser/RegularParser.php", "src/Parser/WordpressParser.php", "src/Serializer/TextSerializer.php"] } +no-shorthand-ternary = { exclude = ["src/Parser/StackParser.php", "src/Parser/RegexParser.php", "src/Parser/RegularParser.php", "src/Parser/WordpressParser.php", "src/Serializer/TextSerializer.php"] } prefer-arrow-function = { enabled = false } prefer-static-closure = { enabled = false } str-contains = { enabled = false } diff --git a/src/Parser/HybridParser.php b/src/Parser/HybridParser.php index 1bfce9f..f3c8723 100644 --- a/src/Parser/HybridParser.php +++ b/src/Parser/HybridParser.php @@ -1,292 +1,30 @@ delimiter = $syntax->getParameterValueDelimiter(); - // @mago-expect analysis:invalid-property-assignment-value - $this->delimiterLength = strlen($this->delimiter); - - $openTag = preg_quote($syntax->getOpeningTag(), '~'); - $closeTag = preg_quote($syntax->getClosingTag(), '~'); - $marker = preg_quote($syntax->getClosingTagMarker(), '~'); - $separator = preg_quote($syntax->getParameterValueSeparator(), '~'); - $delimiter = preg_quote($this->delimiter, '~'); - - $space = '\s*'; - $special = $openTag.'|'.$closeTag.'|'.$marker.'|'.$separator.'|'.$delimiter; - $notSpecial = '(?!'.$special.')'; - // a single "string token": one escape sequence, or one maximal run of - // non-special, non-whitespace characters (possessive so it never gives back) - $stringToken = '(?:\\\\.|(?:'.$notSpecial.'[^\s\\\\])++)'; - // a value globs consecutive string tokens; atomic so the lexer commits like - // RegularParser instead of backtracking into a different tokenization - $stringRun = '(?>'.$stringToken.'++)'; - // a delimited value; the body is possessive so an escape sequence is never - // given back to let the value re-close at an earlier (escaped) delimiter - $quoted = $delimiter.'(?:\\\\.|(?!'.$delimiter.').)*+'.$delimiter; - $value = '(?>'.$quoted.'|'.$stringRun.')'; - // shortcode name; must end on a token boundary so `[foo.bar]` is rejected wholesale - $name = '(?:'.$notSpecial.'[a-zA-Z0-9_*-])++'; - $boundary = '(?=\s|'.$special.'|$)'; - // a parameter name is a single string token, not a glued run - $parameters = '(?(?:'.$space.$stringToken.'(?:'.$space.$separator.$space.$value.')?)*+)'; - $bbCode = '(?:'.$separator.$space.'(?'.$value.')'.$space.')?+'; - - $closingTagRule = $openTag.$space.$marker.$space.'(?'.$name.')'.$space.$closeTag; - $openingTagRule = $openTag.$space.'(?'.$name.')'.$boundary.$space.$bbCode.$parameters.$space.'(?'.$marker.')?'.$space.$closeTag; - - $this->tagRegex = '~\\\\.(*SKIP)(*FAIL)|(?:'.$closingTagRule.'|'.$openingTagRule.')~us'; - $this->paramRegex = '~'.$space.'(?'.$stringToken.')(?:'.$space.$separator.$space.'(?'.$value.'))?~us'; - } - - /** - * @param string $text - * - * @return ParsedShortcode[] - */ - public function parse($text) - { - // @mago-expect analysis:reference-to-undefined-variable - $count = preg_match_all($this->tagRegex, $text, $matches, PREG_OFFSET_CAPTURE); - if(false === $count || preg_last_error() !== PREG_NO_ERROR) { - throw new \RuntimeException(sprintf('PCRE failure `%s`.', preg_last_error())); - } - if(0 === $count) { - return array(); - } - - // pure-ASCII text lets us treat byte offsets as character offsets directly - $ascii = !preg_match('~[\x80-\xff]~', $text); - $lastByte = 0; - $lastChar = 0; - - /** @psalm-var list $nodes */ - $nodes = array(); - /** @psalm-var list $stack */ - $stack = array(); - $depth = 0; - $openNames = array(); - // @mago-expect analysis:mismatched-array-index - $closeNames = $matches['cname']; - // @mago-expect analysis:mismatched-array-index - $names = $matches['name']; - // @mago-expect analysis:mismatched-array-index - $selfMarkers = $matches['self']; - // @mago-expect analysis:mismatched-array-index - $bbCodes = $matches['bbCode']; - // @mago-expect analysis:mismatched-array-index - $paramStrings = $matches['params']; - - foreach($matches[0] as $index => $whole) { - $byteStart = $whole[1]; - // @mago-expect analysis:invalid-operand, analysis:mixed-assignment - $byteEnd = $byteStart + strlen($whole[0]); - - // @mago-expect analysis:redundant-comparison, analysis:redundant-logical-operation - if(isset($closeNames[$index][1]) && $closeNames[$index][1] !== -1) { - // closing tag: match the innermost open node of the same name. - // RegularParser rejects a closing name that is falsy in PHP (`'0'`) - // via `if(!$closingName = ...)`, so we faithfully ignore it too. - $closeName = $closeNames[$index][0]; - if('0' === $closeName) { - continue; - } - for($stackIndex = $depth - 1; $stackIndex >= 0; $stackIndex--) { - if(!isset($openNames[$closeName]) || 0 === $openNames[$closeName]) { - break; - } - $nodeIndex = $stack[$stackIndex]; - if($nodes[$nodeIndex][0] === $closeName) { - $nodes[$nodeIndex][7] = true; // closed - $nodes[$nodeIndex][8] = $byteStart; // closeStart - $nodes[$nodeIndex][9] = $byteEnd; // closeEnd - for($pop = $stackIndex; $pop < $depth; $pop++) { - $openNames[$nodes[$stack[$pop]][0]]--; - } - $depth = $stackIndex; - break; - } - } - continue; - } - - // opening tag — char offset (byte offset is fine for pure-ASCII text) - if($ascii) { - $offset = $byteStart; - } else { - if($byteStart > $lastByte) { - /** @psalm-suppress PossiblyFalseArgument */ - // @mago-expect analysis:invalid-operand, analysis:possibly-invalid-operand, analysis:possibly-invalid-argument, analysis:mixed-argument - $lastChar += mb_strlen(substr($text, $lastByte, $byteStart - $lastByte), 'utf-8'); - $lastByte = $byteStart; - } - $offset = $lastChar; - } - - // @mago-expect analysis:redundant-isset-check - // @mago-expect analysis:redundant-comparison, analysis:redundant-logical-operation - $selfClosing = isset($selfMarkers[$index][1]) && $selfMarkers[$index][1] !== -1; - - // node tuple: [0]name [1]paramsRaw [2]bbCodeRaw [3]offset [4]start - // [5]openEnd [6]parent [7]closed [8]closeStart [9]closeEnd [10]selfClosing - // parameter/bbCode parsing is deferred to build() so absorbed nodes never pay for it - $nodes[] = array( - $names[$index][0], - // @mago-expect analysis:redundant-comparison, analysis:redundant-logical-operation - isset($paramStrings[$index][1]) && $paramStrings[$index][1] !== -1 ? $paramStrings[$index][0] : '', - // @mago-expect analysis:redundant-comparison, analysis:redundant-logical-operation - isset($bbCodes[$index][1]) && $bbCodes[$index][1] !== -1 ? $bbCodes[$index][0] : null, - $offset, - $byteStart, - $byteEnd, - $depth ? $stack[$depth - 1] : null, - $selfClosing, - $selfClosing ? $byteEnd : null, - $selfClosing ? $byteEnd : null, - $selfClosing, - ); - - if(false === $selfClosing) { - $stack[$depth++] = count($nodes) - 1; - $openName = $names[$index][0]; - $openNames[$openName] = isset($openNames[$openName]) ? $openNames[$openName] + 1 : 1; - } - } - - // @mago-expect analysis:possibly-invalid-argument - return $this->build($nodes, $text); - } - - /** - * @psalm-param array $nodes - * @param string $text - * - * @return ParsedShortcode[] - */ - private function build(array $nodes, $text) - { - $shortcodes = array(); - // A node is absorbed (part of a closed ancestor's content) iff its parent is - // closed or itself absorbed. Parents always precede children, so a single - // forward pass resolves this in O(1) per node instead of walking ancestors. - /** @psalm-var array $absorbed */ - $absorbed = array(); - foreach($nodes as $index => $node) { - $parent = $node[6]; - if(null !== $parent && ($nodes[$parent][7] || $absorbed[$parent])) { - $absorbed[$index] = true; - continue; - } - $absorbed[$index] = false; - - if($node[7]) { - // a closed node always has integer close offsets (set on close or self-close) - /** @psalm-suppress PossiblyNullOperand */ - // @mago-expect analysis:possibly-null-operand - $content = $node[10] ? null : substr($text, $node[5], $node[8] - $node[5]); - /** @psalm-suppress PossiblyNullOperand */ - // @mago-expect analysis:possibly-null-operand - $shortcodeText = substr($text, $node[4], $node[9] - $node[4]); - } else { - $content = null; - $shortcodeText = substr($text, $node[4], $node[5] - $node[4]); - } - - $parameters = '' === $node[1] ? array() : $this->parseParameters($node[1]); - $bbCode = null === $node[2] ? null : $this->extractValue($node[2]); - - /** @psalm-suppress PossiblyFalseArgument */ - $shortcode = new Shortcode($node[0], $parameters, $content, $bbCode); - /** @psalm-suppress PossiblyFalseArgument */ - $shortcodes[] = new ParsedShortcode($shortcode, $shortcodeText, $node[3]); - } - - return $shortcodes; - } +// @mago-expect analysis:unused-statement +class_exists('Thunder\Shortcode\Parser\StackParser'); +/** @psalm-suppress TypeDoesNotContainType */ +// @mago-expect analysis:impossible-condition +if(false) { /** - * @param string $text - * - * @psalm-return array + * @deprecated Use StackParser instead, this alias will be removed in 2.0. */ - private function parseParameters($text) + final class HybridParser implements ParserInterface { - // @mago-expect analysis:reference-to-undefined-variable - if('' === $text || false === preg_match_all($this->paramRegex, $text, $matches, PREG_SET_ORDER)) { + /** @param \Thunder\Shortcode\Syntax\SyntaxInterface|null $syntax */ + public function __construct($syntax = null) + { + } + + /** + * @param string $text + * + * @return \Thunder\Shortcode\Shortcode\ParsedShortcode[] + */ + public function parse($text) + { return array(); } - - $parameters = array(); - foreach($matches as $match) { - if(!isset($match['pn']) || '' === $match['pn']) { - continue; - } - $hasValue = isset($match['pv']) && '' !== $match['pv']; - $parameters[$match['pn']] = $hasValue ? $this->extractValue($match['pv']) : null; - } - - return $parameters; - } - - /** - * @param string $value - * - * @return string - * @psalm-suppress InvalidFalsableReturnType - */ - private function extractValue($value) - { - $length = $this->delimiterLength; - if(strlen($value) >= 2 * $length - && strncmp($value, $this->delimiter, $length) === 0 - && substr($value, -$length) === $this->delimiter) { - /** @psalm-suppress FalsableReturnStatement */ - return substr($value, $length, -$length); - } - - return $value; } } diff --git a/src/Parser/StackParser.php b/src/Parser/StackParser.php new file mode 100644 index 0000000..0ebc9b3 --- /dev/null +++ b/src/Parser/StackParser.php @@ -0,0 +1,294 @@ +delimiter = $syntax->getParameterValueDelimiter(); + // @mago-expect analysis:invalid-property-assignment-value + $this->delimiterLength = strlen($this->delimiter); + + $openTag = preg_quote($syntax->getOpeningTag(), '~'); + $closeTag = preg_quote($syntax->getClosingTag(), '~'); + $marker = preg_quote($syntax->getClosingTagMarker(), '~'); + $separator = preg_quote($syntax->getParameterValueSeparator(), '~'); + $delimiter = preg_quote($this->delimiter, '~'); + + $space = '\s*'; + $special = $openTag.'|'.$closeTag.'|'.$marker.'|'.$separator.'|'.$delimiter; + $notSpecial = '(?!'.$special.')'; + // a single "string token": one escape sequence, or one maximal run of + // non-special, non-whitespace characters (possessive so it never gives back) + $stringToken = '(?:\\\\.|(?:'.$notSpecial.'[^\s\\\\])++)'; + // a value globs consecutive string tokens; atomic so the lexer commits like + // RegularParser instead of backtracking into a different tokenization + $stringRun = '(?>'.$stringToken.'++)'; + // a delimited value; the body is possessive so an escape sequence is never + // given back to let the value re-close at an earlier (escaped) delimiter + $quoted = $delimiter.'(?:\\\\.|(?!'.$delimiter.').)*+'.$delimiter; + $value = '(?>'.$quoted.'|'.$stringRun.')'; + // shortcode name; must end on a token boundary so `[foo.bar]` is rejected wholesale + $name = '(?:'.$notSpecial.'[a-zA-Z0-9_*-])++'; + $boundary = '(?=\s|'.$special.'|$)'; + // a parameter name is a single string token, not a glued run + $parameters = '(?(?:'.$space.$stringToken.'(?:'.$space.$separator.$space.$value.')?)*+)'; + $bbCode = '(?:'.$separator.$space.'(?'.$value.')'.$space.')?+'; + + $closingTagRule = $openTag.$space.$marker.$space.'(?'.$name.')'.$space.$closeTag; + $openingTagRule = $openTag.$space.'(?'.$name.')'.$boundary.$space.$bbCode.$parameters.$space.'(?'.$marker.')?'.$space.$closeTag; + + $this->tagRegex = '~\\\\.(*SKIP)(*FAIL)|(?:'.$closingTagRule.'|'.$openingTagRule.')~us'; + $this->paramRegex = '~'.$space.'(?'.$stringToken.')(?:'.$space.$separator.$space.'(?'.$value.'))?~us'; + } + + /** + * @param string $text + * + * @return ParsedShortcode[] + */ + public function parse($text) + { + // @mago-expect analysis:reference-to-undefined-variable + $count = preg_match_all($this->tagRegex, $text, $matches, PREG_OFFSET_CAPTURE); + if(false === $count || preg_last_error() !== PREG_NO_ERROR) { + throw new \RuntimeException(sprintf('PCRE failure `%s`.', preg_last_error())); + } + if(0 === $count) { + return array(); + } + + // pure-ASCII text lets us treat byte offsets as character offsets directly + $ascii = !preg_match('~[\x80-\xff]~', $text); + $lastByte = 0; + $lastChar = 0; + + /** @psalm-var list $nodes */ + $nodes = array(); + /** @psalm-var list $stack */ + $stack = array(); + $depth = 0; + $openNames = array(); + // @mago-expect analysis:mismatched-array-index + $closeNames = $matches['cname']; + // @mago-expect analysis:mismatched-array-index + $names = $matches['name']; + // @mago-expect analysis:mismatched-array-index + $selfMarkers = $matches['self']; + // @mago-expect analysis:mismatched-array-index + $bbCodes = $matches['bbCode']; + // @mago-expect analysis:mismatched-array-index + $paramStrings = $matches['params']; + + foreach($matches[0] as $index => $whole) { + $byteStart = $whole[1]; + // @mago-expect analysis:invalid-operand, analysis:mixed-assignment + $byteEnd = $byteStart + strlen($whole[0]); + + // @mago-expect analysis:redundant-comparison, analysis:redundant-logical-operation + if(isset($closeNames[$index][1]) && $closeNames[$index][1] !== -1) { + // closing tag: match the innermost open node of the same name. + // RegularParser rejects a closing name that is falsy in PHP (`'0'`) + // via `if(!$closingName = ...)`, so we faithfully ignore it too. + $closeName = $closeNames[$index][0]; + if('0' === $closeName) { + continue; + } + for($stackIndex = $depth - 1; $stackIndex >= 0; $stackIndex--) { + if(!isset($openNames[$closeName]) || 0 === $openNames[$closeName]) { + break; + } + $nodeIndex = $stack[$stackIndex]; + if($nodes[$nodeIndex][0] === $closeName) { + $nodes[$nodeIndex][7] = true; // closed + $nodes[$nodeIndex][8] = $byteStart; // closeStart + $nodes[$nodeIndex][9] = $byteEnd; // closeEnd + for($pop = $stackIndex; $pop < $depth; $pop++) { + $openNames[$nodes[$stack[$pop]][0]]--; + } + $depth = $stackIndex; + break; + } + } + continue; + } + + // opening tag — char offset (byte offset is fine for pure-ASCII text) + if($ascii) { + $offset = $byteStart; + } else { + if($byteStart > $lastByte) { + /** @psalm-suppress PossiblyFalseArgument */ + // @mago-expect analysis:invalid-operand, analysis:possibly-invalid-operand, analysis:possibly-invalid-argument, analysis:mixed-argument + $lastChar += mb_strlen(substr($text, $lastByte, $byteStart - $lastByte), 'utf-8'); + $lastByte = $byteStart; + } + $offset = $lastChar; + } + + // @mago-expect analysis:redundant-isset-check + // @mago-expect analysis:redundant-comparison, analysis:redundant-logical-operation + $selfClosing = isset($selfMarkers[$index][1]) && $selfMarkers[$index][1] !== -1; + + // node tuple: [0]name [1]paramsRaw [2]bbCodeRaw [3]offset [4]start + // [5]openEnd [6]parent [7]closed [8]closeStart [9]closeEnd [10]selfClosing + // parameter/bbCode parsing is deferred to build() so absorbed nodes never pay for it + $nodes[] = array( + $names[$index][0], + // @mago-expect analysis:redundant-comparison, analysis:redundant-logical-operation + isset($paramStrings[$index][1]) && $paramStrings[$index][1] !== -1 ? $paramStrings[$index][0] : '', + // @mago-expect analysis:redundant-comparison, analysis:redundant-logical-operation + isset($bbCodes[$index][1]) && $bbCodes[$index][1] !== -1 ? $bbCodes[$index][0] : null, + $offset, + $byteStart, + $byteEnd, + $depth ? $stack[$depth - 1] : null, + $selfClosing, + $selfClosing ? $byteEnd : null, + $selfClosing ? $byteEnd : null, + $selfClosing, + ); + + if(false === $selfClosing) { + $stack[$depth++] = count($nodes) - 1; + $openName = $names[$index][0]; + $openNames[$openName] = isset($openNames[$openName]) ? $openNames[$openName] + 1 : 1; + } + } + + // @mago-expect analysis:possibly-invalid-argument + return $this->build($nodes, $text); + } + + /** + * @psalm-param array $nodes + * @param string $text + * + * @return ParsedShortcode[] + */ + private function build(array $nodes, $text) + { + $shortcodes = array(); + // A node is absorbed (part of a closed ancestor's content) iff its parent is + // closed or itself absorbed. Parents always precede children, so a single + // forward pass resolves this in O(1) per node instead of walking ancestors. + /** @psalm-var array $absorbed */ + $absorbed = array(); + foreach($nodes as $index => $node) { + $parent = $node[6]; + if(null !== $parent && ($nodes[$parent][7] || $absorbed[$parent])) { + $absorbed[$index] = true; + continue; + } + $absorbed[$index] = false; + + if($node[7]) { + // a closed node always has integer close offsets (set on close or self-close) + /** @psalm-suppress PossiblyNullOperand */ + // @mago-expect analysis:possibly-null-operand + $content = $node[10] ? null : substr($text, $node[5], $node[8] - $node[5]); + /** @psalm-suppress PossiblyNullOperand */ + // @mago-expect analysis:possibly-null-operand + $shortcodeText = substr($text, $node[4], $node[9] - $node[4]); + } else { + $content = null; + $shortcodeText = substr($text, $node[4], $node[5] - $node[4]); + } + + $parameters = '' === $node[1] ? array() : $this->parseParameters($node[1]); + $bbCode = null === $node[2] ? null : $this->extractValue($node[2]); + + /** @psalm-suppress PossiblyFalseArgument */ + $shortcode = new Shortcode($node[0], $parameters, $content, $bbCode); + /** @psalm-suppress PossiblyFalseArgument */ + $shortcodes[] = new ParsedShortcode($shortcode, $shortcodeText, $node[3]); + } + + return $shortcodes; + } + + /** + * @param string $text + * + * @psalm-return array + */ + private function parseParameters($text) + { + // @mago-expect analysis:reference-to-undefined-variable + if('' === $text || false === preg_match_all($this->paramRegex, $text, $matches, PREG_SET_ORDER)) { + return array(); + } + + $parameters = array(); + foreach($matches as $match) { + if(!isset($match['pn']) || '' === $match['pn']) { + continue; + } + $hasValue = isset($match['pv']) && '' !== $match['pv']; + $parameters[$match['pn']] = $hasValue ? $this->extractValue($match['pv']) : null; + } + + return $parameters; + } + + /** + * @param string $value + * + * @return string + * @psalm-suppress InvalidFalsableReturnType + */ + private function extractValue($value) + { + $length = $this->delimiterLength; + if(strlen($value) >= 2 * $length + && strncmp($value, $this->delimiter, $length) === 0 + && substr($value, -$length) === $this->delimiter) { + /** @psalm-suppress FalsableReturnStatement */ + return substr($value, $length, -$length); + } + + return $value; + } +} + +class_alias('Thunder\Shortcode\Parser\StackParser', 'Thunder\Shortcode\Parser\HybridParser'); diff --git a/tests/ParserTest.php b/tests/ParserTest.php index 7cadcaa..fa0bd60 100644 --- a/tests/ParserTest.php +++ b/tests/ParserTest.php @@ -2,8 +2,11 @@ namespace Thunder\Shortcode\Tests; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\PreserveGlobalState; +use PHPUnit\Framework\Attributes\RunInSeparateProcess; use Thunder\Shortcode\HandlerContainer\HandlerContainer; use Thunder\Shortcode\Parser\RegularParser; +use Thunder\Shortcode\Parser\StackParser; use Thunder\Shortcode\Parser\HybridParser; use Thunder\Shortcode\Parser\ParserInterface; use Thunder\Shortcode\Parser\RegexParser; @@ -20,7 +23,7 @@ final class ParserTest extends AbstractTestCase { public function testParsersCountOffsetsInCharacters() { - foreach(array(new RegularParser(), new HybridParser()) as $parser) { + foreach(array(new RegularParser(), new StackParser(), new HybridParser()) as $parser) { $this->assertShortcodes($parser->parse('żż[a]x[/a]'), array( new ParsedShortcode(new Shortcode('a', array(), 'x', null), '[a]x[/a]', 2), )); @@ -30,7 +33,7 @@ public function testParsersCountOffsetsInCharacters() public function testParsersWithRegexSpecialCharactersInSyntax() { $syntax = new Syntax('[', ']', '.', '*', '|'); - foreach(array(new RegularParser($syntax), new HybridParser($syntax), new RegexParser($syntax)) as $parser) { + foreach(array(new RegularParser($syntax), new StackParser($syntax), new HybridParser($syntax), new RegexParser($syntax)) as $parser) { $this->assertShortcodes($parser->parse('[a b*|x y|]c[.a]'), array( new ParsedShortcode(new Shortcode('a', array('b' => 'x y'), 'c', null), '[a b*|x y|]c[.a]', 0), )); @@ -57,6 +60,7 @@ public function testExceptionOnInvalidParserSyntax() { $classes = array( 'Thunder\Shortcode\Parser\RegularParser', + 'Thunder\Shortcode\Parser\StackParser', 'Thunder\Shortcode\Parser\HybridParser', 'Thunder\Shortcode\Parser\RegexParser', ); @@ -70,6 +74,13 @@ public function testExceptionOnInvalidParserSyntax() } } + public function testStackParserExceptionOnInvalidUtf8() + { + $parser = new StackParser(); + $this->willThrowException('RuntimeException'); + $parser->parse("[a]\xff[/a]"); + } + public function testHybridParserExceptionOnInvalidUtf8() { $parser = new HybridParser(); @@ -108,7 +119,7 @@ public function testParsersHandleLongRunsOfEscapes() { $value = str_repeat('a\\x', 9000); $text = '[a k='.$value.']x[/a] [b /]'; - foreach(array(new RegularParser(), new HybridParser()) as $parser) { + foreach(array(new RegularParser(), new StackParser(), new HybridParser()) as $parser) { $this->assertShortcodes($parser->parse($text), array( new ParsedShortcode(new Shortcode('a', array('k' => $value), 'x', null), '[a k='.$value.']x[/a]', 0), new ParsedShortcode(new Shortcode('b', array(), null, null), '[b /]', 27012), @@ -326,6 +337,7 @@ public static function provideShortcodes() $syntax = array_shift($test); $result[] = array_merge(array(new RegexParser($syntax)), $test); + $result[] = array_merge(array(new StackParser($syntax)), $test); $result[] = array_merge(array(new HybridParser($syntax)), $test); $result[] = array_merge(array(new RegularParser($syntax)), $test); if(!in_array($key, $wordpressSkip, true)) { @@ -336,7 +348,7 @@ public static function provideShortcodes() return $result; } - public function testHybridParserMatchesRegularParserOnUnbalancedTags() + public function testStackParserMatchesRegularParserOnUnbalancedTags() { $inputs = array( '[/x][a][/b]x[/a][/a][/c]', @@ -353,16 +365,18 @@ public function testHybridParserMatchesRegularParserOnUnbalancedTags() ); $regular = new RegularParser(); + $stack = new StackParser(); $hybrid = new HybridParser(); foreach($inputs as $input) { + $this->assertShortcodes($stack->parse($input), $regular->parse($input)); $this->assertShortcodes($hybrid->parse($input), $regular->parse($input)); } } public function testIssue77() { - // HybridParser must reproduce RegularParser's backtracking behaviour exactly - foreach(array(new RegularParser(), new HybridParser()) as $parser) { + // StackParser must reproduce RegularParser's backtracking behaviour exactly + foreach(array(new RegularParser(), new StackParser(), new HybridParser()) as $parser) { $this->assertShortcodes($parser->parse('[a][x][/x][x k="v][/x][y]x[/y]'), array( new ParsedShortcode(new Shortcode('a', array(), null, null), '[a]', 0), new ParsedShortcode(new Shortcode('x', array(), '', null), '[x][/x]', 3), @@ -375,9 +389,9 @@ public function testIssue77() } } - public function testHybridParserSkipsEscapedTags() + public function testStackParserSkipsEscapedTags() { - foreach(array(new RegularParser(), new HybridParser()) as $parser) { + foreach(array(new RegularParser(), new StackParser(), new HybridParser()) as $parser) { $this->assertShortcodes($parser->parse('\\[a] [b]'), array( new ParsedShortcode(new Shortcode('b', array(), null, null), '[b]', 5), )); @@ -432,6 +446,7 @@ public static function provideRunsOfOpeningTags() $result = array(); foreach($cases as $case) { $result[] = array(new RegularParser($case[0]), $case[1], $case[2]); + $result[] = array(new StackParser($case[0]), $case[1], $case[2]); $result[] = array(new HybridParser($case[0]), $case[1], $case[2]); } @@ -447,7 +462,7 @@ public function testIssue119() '[a k="x\"y"]inner[/a]' => new ParsedShortcode(new Shortcode('a', array('k' => 'x\"y'), 'inner', null), '[a k="x\"y"]inner[/a]', 0), '[mention id=1 name="foo\"ff\""][/mention]' => new ParsedShortcode(new Shortcode('mention', array('id' => '1', 'name' => 'foo\"ff\"'), '', null), '[mention id=1 name="foo\"ff\""][/mention]', 0), ); - foreach(array(new RegularParser(), new HybridParser()) as $parser) { + foreach(array(new RegularParser(), new StackParser(), new HybridParser()) as $parser) { foreach($cases as $input => $expected) { $this->assertShortcodes($parser->parse($input), array($expected)); } @@ -509,7 +524,7 @@ public function testWordPress() public function testParsersHandleLongUnbrokenText() { $text = '[a]x[/a] '.str_repeat('Q', 50000).' [b /]'; - foreach(array(new RegularParser(), new HybridParser(), new RegexParser(), new WordpressParser()) as $parser) { + foreach(array(new RegularParser(), new StackParser(), new HybridParser(), new RegexParser(), new WordpressParser()) as $parser) { $this->assertShortcodes($parser->parse($text), array( new ParsedShortcode(new Shortcode('a', array(), 'x', null), '[a]x[/a]', 0), new ParsedShortcode(new Shortcode('b', array(), null, null), '[b /]', 50010), @@ -526,14 +541,33 @@ public function testWordpressInvalidNamesException() public function testInstances() { static::assertInstanceOf('Thunder\Shortcode\Parser\WordPressParser', new WordpressParser()); + static::assertInstanceOf('Thunder\Shortcode\Parser\StackParser', new StackParser()); static::assertInstanceOf('Thunder\Shortcode\Parser\HybridParser', new HybridParser()); static::assertInstanceOf('Thunder\Shortcode\Parser\RegularParser', new RegularParser()); } + public function testHybridParserAliasesStackParser() + { + static::assertSame('Thunder\Shortcode\Parser\StackParser', get_class(new \Thunder\Shortcode\Parser\HybridParser())); + static::assertInstanceOf('Thunder\Shortcode\Parser\HybridParser', new StackParser()); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + #[RunInSeparateProcess] + #[PreserveGlobalState(false)] + public function testHybridParserLoadsStackParser() + { + static::assertFalse(class_exists('Thunder\Shortcode\Parser\StackParser', false)); + static::assertInstanceOf('Thunder\Shortcode\Parser\StackParser', new \Thunder\Shortcode\Parser\HybridParser()); + } + public function testParsersEndNamesAtSyntaxTokens() { $syntax = new Syntax('(', ')', '*', '=', '"'); - foreach(array(new RegularParser($syntax), new HybridParser($syntax)) as $parser) { + foreach(array(new RegularParser($syntax), new StackParser($syntax), new HybridParser($syntax)) as $parser) { $this->assertShortcodes($parser->parse('(a*) (b)x(*b) (c*d)'), array( new ParsedShortcode(new Shortcode('a', array(), null, null), '(a*)', 0), new ParsedShortcode(new Shortcode('b', array(), 'x', null), '(b)x(*b)', 5), diff --git a/tests/ProcessorTest.php b/tests/ProcessorTest.php index 7dbc843..0a25fbc 100644 --- a/tests/ProcessorTest.php +++ b/tests/ProcessorTest.php @@ -217,6 +217,7 @@ public function testProcessorKeepsMultibyteTextAroundShortcodes() { $parsers = array( new RegularParser(), + new \Thunder\Shortcode\Parser\StackParser(), new \Thunder\Shortcode\Parser\HybridParser(), new RegexParser(), new \Thunder\Shortcode\Parser\WordpressParser(), @@ -235,7 +236,7 @@ public function testBaseOffsetCountsCharacters() $handlers = $this->getHandlers(); $handlers->add('offset', function (ProcessedShortcode $s) { return (string)$s->getBaseOffset(); }); - foreach(array(new RegularParser(), new \Thunder\Shortcode\Parser\HybridParser()) as $parser) { + foreach(array(new RegularParser(), new \Thunder\Shortcode\Parser\StackParser(), new \Thunder\Shortcode\Parser\HybridParser()) as $parser) { $processor = new Processor($parser, $handlers); static::assertSame('9', $processor->process('[c x="ż"][offset /][/c]'), get_class($parser)); }