9
9
*/
10
10
class Comment
11
11
{
12
+ /** @var bool If current char is within a string */
13
+ protected $ inStr = false ;
14
+
15
+ /** @var int Lines of comments 0 = no comment, 1 = single line, 2 = multi lines */
16
+ protected $ comment = 0 ;
17
+
12
18
/**
13
19
* Strip comments from JSON string.
14
20
*
@@ -22,40 +28,21 @@ public function strip($json)
22
28
return $ json ;
23
29
}
24
30
25
- $ index = -1 ;
26
- $ inStr = false ;
27
- $ return = '' ;
28
- $ char = '' ;
29
- $ comment = 'none ' ;
31
+ list ($ index , $ return , $ char ) = [-1 , '' , '' ];
30
32
31
33
while (isset ($ json [++$ index ])) {
32
34
list ($ prev , $ char ) = [$ char , $ json [$ index ]];
33
35
34
- if ('none ' === $ comment && $ char === '" ' && $ prev !== '\\' ) {
35
- $ inStr = !$ inStr ;
36
- }
37
-
38
36
$ charnext = $ char . (isset ($ json [$ index + 1 ]) ? $ json [$ index + 1 ] : '' );
39
-
40
- if (!$ inStr && 'none ' === $ comment ) {
41
- $ comment = $ charnext === '// ' ? 'single ' : ($ charnext === '/* ' ? 'multi ' : 'none ' );
42
- }
43
-
44
- if ($ inStr || 'none ' === $ comment ) {
37
+ if ($ this ->inStringOrCommentEnd ($ prev , $ char , $ charnext )) {
45
38
$ return .= $ char ;
46
39
47
40
continue ;
48
41
}
49
42
50
- if (($ comment === 'single ' && $ char == "\n" )
51
- || ($ comment === 'multi ' && $ charnext == '*/ ' )
52
- ) {
53
- // Cosmetic fix only!
54
- if ($ comment === 'single ' ) {
55
- $ return = rtrim ($ return ) . $ char ;
56
- }
57
-
58
- $ comment = 'none ' ;
43
+ $ wasSingle = 1 === $ this ->comment ;
44
+ if ($ this ->hasCommentEnded ($ char , $ charnext ) && $ wasSingle ) {
45
+ $ return = rtrim ($ return ) . $ char ;
59
46
}
60
47
61
48
$ index += $ charnext === '*/ ' ? 1 : 0 ;
@@ -64,6 +51,33 @@ public function strip($json)
64
51
return $ return ;
65
52
}
66
53
54
+ protected function inStringOrCommentEnd ($ prev , $ char , $ charnext )
55
+ {
56
+ if (0 === $ this ->comment && $ char === '" ' && $ prev !== '\\' ) {
57
+ $ this ->inStr = !$ this ->inStr ;
58
+ }
59
+
60
+ if (!$ this ->inStr && 0 === $ this ->comment ) {
61
+ $ this ->comment = $ charnext === '// ' ? 1 : ($ charnext === '/* ' ? 2 : 0 );
62
+ }
63
+
64
+ return $ this ->inStr || 0 === $ this ->comment ;
65
+ }
66
+
67
+ protected function hasCommentEnded ($ char , $ charnext )
68
+ {
69
+ $ singleEnded = $ this ->comment === 1 && $ char == "\n" ;
70
+ $ multiEnded = $ this ->comment === 2 && $ charnext == '*/ ' ;
71
+
72
+ if ($ singleEnded || $ multiEnded ) {
73
+ $ this ->comment = 0 ;
74
+
75
+ return true ;
76
+ }
77
+
78
+ return false ;
79
+ }
80
+
67
81
/**
68
82
* Strip comments and decode JSON string.
69
83
*
0 commit comments