Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions src/Comment.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
24 changes: 24 additions & 0 deletions tests/CommentTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 [
Expand Down