From edaa39adfb53867d9528729a35cc283ff9f90bc5 Mon Sep 17 00:00:00 2001 From: Daniel Ziegenberg Date: Sat, 24 Aug 2024 13:41:40 +0200 Subject: [PATCH] [BUGFIX] Fix comment parsing to support multiple comments Because of an eager consumption of whitespace, the rule parsing would swallow a trailing comment, meaning the comment for the next rule would be affected. This patch addresses this by only consuming real whitespace without comments after a rule. Fixes #173 Signed-off-by: Daniel Ziegenberg --- src/Parsing/ParserState.php | 12 ++++++++++-- src/Rule/Rule.php | 2 +- tests/ParserTest.php | 11 +++++++---- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/Parsing/ParserState.php b/src/Parsing/ParserState.php index cbfa89c9..868d6432 100644 --- a/src/Parsing/ParserState.php +++ b/src/Parsing/ParserState.php @@ -220,18 +220,26 @@ public function parseCharacter($bIsForIdentifier) } /** - * @return array|void + * Consumes whitespace and comments and returns the comments. + * If $withoutComment is true, only whitespace is consumed. + * + * @param bool $withoutComment Do not consume comments, only whitespace. + * + * @return array|void List of comments. * * @throws UnexpectedEOFException * @throws UnexpectedTokenException */ - public function consumeWhiteSpace(): array + public function consumeWhiteSpace(bool $withoutComment = false): array { $aComments = []; do { while (\preg_match('/\\s/isSu', $this->peek()) === 1) { $this->consume(1); } + if ($withoutComment) { + break; + } if ($this->oParserSettings->bLenientParsing) { try { $oComment = $this->consumeComment(); diff --git a/src/Rule/Rule.php b/src/Rule/Rule.php index ca9f380c..0546ae91 100644 --- a/src/Rule/Rule.php +++ b/src/Rule/Rule.php @@ -105,7 +105,7 @@ public static function parse(ParserState $oParserState): Rule while ($oParserState->comes(';')) { $oParserState->consume(';'); } - $oParserState->consumeWhiteSpace(); + $oParserState->consumeWhiteSpace(true); return $oRule; } diff --git a/tests/ParserTest.php b/tests/ParserTest.php index 2c1c7287..2d50d913 100644 --- a/tests/ParserTest.php +++ b/tests/ParserTest.php @@ -1161,13 +1161,16 @@ public function commentExtracting(): void */ public function flatCommentExtracting(): void { - $parser = new Parser('div {/*Find Me!*/left:10px; text-align:left;}'); + $parser = new Parser('div {/*Find Me!*/left:10px; /*Find Me Too!*/text-align:left;}'); $doc = $parser->parse(); $contents = $doc->getContents(); $divRules = $contents[0]->getRules(); - $comments = $divRules[0]->getComments(); - self::assertCount(1, $comments); - self::assertSame('Find Me!', $comments[0]->getComment()); + $rule1Comments = $divRules[0]->getComments(); + $rule2Comments = $divRules[1]->getComments(); + self::assertCount(1, $rule1Comments); + self::assertCount(1, $rule2Comments); + self::assertEquals('Find Me!', $rule1Comments[0]->getComment()); + self::assertEquals('Find Me Too!', $rule2Comments[0]->getComment()); } /**