diff --git a/src/Comment.php b/src/Comment.php index d4e1764..418c66e 100644 --- a/src/Comment.php +++ b/src/Comment.php @@ -63,11 +63,12 @@ protected function doStrip(string $json): string $crlf = ["\n" => '\n', "\r" => '\r']; while (isset($json[++$this->index])) { + $oldprev = $prev ?? ''; list($prev, $char, $next) = $this->getSegments($json); $return = $this->checkTrail($char, $return); - if ($this->inStringOrCommentEnd($prev, $char, $char . $next)) { + if ($this->inStringOrCommentEnd($prev, $char, $char . $next, $oldprev)) { $return .= $this->inStr && isset($crlf[$char]) ? $crlf[$char] : $char; continue; @@ -115,19 +116,19 @@ protected function checkTrail(string $char, string $json): string return $json; } - protected function inStringOrCommentEnd(string $prev, string $char, string $next): bool + protected function inStringOrCommentEnd(string $prev, string $char, string $next, string $oldprev): bool { - return $this->inString($char, $prev, $next) || $this->inCommentEnd($next); + return $this->inString($char, $prev, $next, $oldprev) || $this->inCommentEnd($next); } - protected function inString(string $char, string $prev, string $next): bool + protected function inString(string $char, string $prev, string $next, string $oldprev): bool { if (0 === $this->comment && $char === '"' && $prev !== '\\') { return $this->inStr = !$this->inStr; } if ($this->inStr && \in_array($next, ['":', '",', '"]', '"}'], true)) { - $this->inStr = false; + $this->inStr = "$oldprev$prev" !== '\\\\'; } return $this->inStr; diff --git a/tests/CommentTest.php b/tests/CommentTest.php index af763f2..654769e 100644 --- a/tests/CommentTest.php +++ b/tests/CommentTest.php @@ -64,9 +64,33 @@ public function testParseFromFile() $parsed = Comment::parseFromFile(__DIR__ . '/composer.json', true); $this->assertTrue(is_array($parsed)); + $this->assertNotEmpty($parsed); $this->assertSame('adhocore/json-comment', $parsed['name']); } + public function testSubJson() + { + // https://github.com/adhocore/php-json-comment/issues/15 + $parsed = Comment::parse('{ + "jo": "{ + /* comment */ + \"url\": \"http://example.com\"//comment + }", + "x": { + /* comment 1 + comment 2 */ + "y": { + // comment + "XY\\\": "//no comment/*", + }, + } + }', true); + + $this->assertArrayHasKey('jo', $parsed); + $this->assertSame('//no comment/*', $parsed['x']['y']['XY\\']); + $this->assertSame('http://example.com', Comment::parse($parsed['jo'])->url); + } + public function theTests() { return [