Skip to content

Commit ecb4e29

Browse files
authored
Merge pull request #16 from adhocore/15-sub-json
2 parents e3628de + 41926bb commit ecb4e29

File tree

2 files changed

+30
-5
lines changed

2 files changed

+30
-5
lines changed

src/Comment.php

+6-5
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,12 @@ protected function doStrip(string $json): string
6363
$crlf = ["\n" => '\n', "\r" => '\r'];
6464

6565
while (isset($json[++$this->index])) {
66+
$oldprev = $prev ?? '';
6667
list($prev, $char, $next) = $this->getSegments($json);
6768

6869
$return = $this->checkTrail($char, $return);
6970

70-
if ($this->inStringOrCommentEnd($prev, $char, $char . $next)) {
71+
if ($this->inStringOrCommentEnd($prev, $char, $char . $next, $oldprev)) {
7172
$return .= $this->inStr && isset($crlf[$char]) ? $crlf[$char] : $char;
7273

7374
continue;
@@ -115,19 +116,19 @@ protected function checkTrail(string $char, string $json): string
115116
return $json;
116117
}
117118

118-
protected function inStringOrCommentEnd(string $prev, string $char, string $next): bool
119+
protected function inStringOrCommentEnd(string $prev, string $char, string $next, string $oldprev): bool
119120
{
120-
return $this->inString($char, $prev, $next) || $this->inCommentEnd($next);
121+
return $this->inString($char, $prev, $next, $oldprev) || $this->inCommentEnd($next);
121122
}
122123

123-
protected function inString(string $char, string $prev, string $next): bool
124+
protected function inString(string $char, string $prev, string $next, string $oldprev): bool
124125
{
125126
if (0 === $this->comment && $char === '"' && $prev !== '\\') {
126127
return $this->inStr = !$this->inStr;
127128
}
128129

129130
if ($this->inStr && \in_array($next, ['":', '",', '"]', '"}'], true)) {
130-
$this->inStr = false;
131+
$this->inStr = "$oldprev$prev" !== '\\\\';
131132
}
132133

133134
return $this->inStr;

tests/CommentTest.php

+24
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,33 @@ public function testParseFromFile()
6464
$parsed = Comment::parseFromFile(__DIR__ . '/composer.json', true);
6565

6666
$this->assertTrue(is_array($parsed));
67+
$this->assertNotEmpty($parsed);
6768
$this->assertSame('adhocore/json-comment', $parsed['name']);
6869
}
6970

71+
public function testSubJson()
72+
{
73+
// https://github.com/adhocore/php-json-comment/issues/15
74+
$parsed = Comment::parse('{
75+
"jo": "{
76+
/* comment */
77+
\"url\": \"http://example.com\"//comment
78+
}",
79+
"x": {
80+
/* comment 1
81+
comment 2 */
82+
"y": {
83+
// comment
84+
"XY\\\": "//no comment/*",
85+
},
86+
}
87+
}', true);
88+
89+
$this->assertArrayHasKey('jo', $parsed);
90+
$this->assertSame('//no comment/*', $parsed['x']['y']['XY\\']);
91+
$this->assertSame('http://example.com', Comment::parse($parsed['jo'])->url);
92+
}
93+
7094
public function theTests()
7195
{
7296
return [

0 commit comments

Comments
 (0)