99 */
1010class Comment
1111{
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+
1218 /**
1319 * Strip comments from JSON string.
1420 *
@@ -22,40 +28,21 @@ public function strip($json)
2228 return $ json ;
2329 }
2430
25- $ index = -1 ;
26- $ inStr = false ;
27- $ return = '' ;
28- $ char = '' ;
29- $ comment = 'none ' ;
31+ list ($ index , $ return , $ char ) = [-1 , '' , '' ];
3032
3133 while (isset ($ json [++$ index ])) {
3234 list ($ prev , $ char ) = [$ char , $ json [$ index ]];
3335
34- if ('none ' === $ comment && $ char === '" ' && $ prev !== '\\' ) {
35- $ inStr = !$ inStr ;
36- }
37-
3836 $ 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 )) {
4538 $ return .= $ char ;
4639
4740 continue ;
4841 }
4942
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 ;
5946 }
6047
6148 $ index += $ charnext === '*/ ' ? 1 : 0 ;
@@ -64,6 +51,33 @@ public function strip($json)
6451 return $ return ;
6552 }
6653
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+
6781 /**
6882 * Strip comments and decode JSON string.
6983 *
0 commit comments