44
55namespace Rector \CodingStyle \Rector \String_ ;
66
7+ use Nette \Utils \Validators ;
78use PhpParser \Node ;
89use PhpParser \Node \Scalar \String_ ;
910use Rector \NodeTypeResolver \Node \AttributeKey ;
@@ -28,6 +29,11 @@ final class SimplifyQuoteEscapeRector extends AbstractRector
2829 */
2930 private const string HAS_NON_PRINTABLE_CHARS = '#[\x00-\x1F\x80-\xFF]# ' ;
3031
32+ /**
33+ * @see https://regex101.com/r/tY7eKW/1
34+ */
35+ private const string CONTROL_CHARS_REGEX = '#[\x00-\x1F]# ' ;
36+
3137 private bool $ hasChanged = false ;
3238
3339 public function getRuleDefinition (): RuleDefinition
@@ -77,7 +83,7 @@ public function refactor(Node $node): ?String_
7783 {
7884 $ this ->hasChanged = false ;
7985
80- if (StringUtils :: isMatch ($ node ->value , self :: HAS_NON_PRINTABLE_CHARS )) {
86+ if ($ this -> hasNonPrintableChars ($ node ->value )) {
8187 return null ;
8288 }
8389
@@ -125,6 +131,11 @@ private function processDoubleQuoted(String_ $string, int $singleQuoteCount, int
125131 return ;
126132 }
127133
134+ // contains escape sequence that will be printed as raw char, e.g. "\u{00A0}"
135+ if ($ this ->hasEscapeSequence ($ string )) {
136+ return ;
137+ }
138+
128139 $ string ->setAttribute (AttributeKey::KIND , String_::KIND_SINGLE_QUOTED );
129140 // invoke override
130141 $ string ->setAttribute (AttributeKey::ORIGINAL_NODE , null );
@@ -137,4 +148,29 @@ private function isMatchEscapedChars(string $string): bool
137148 {
138149 return StringUtils ::isMatch ($ string , self ::ESCAPED_CHAR_REGEX );
139150 }
151+
152+ private function hasEscapeSequence (String_ $ string ): bool
153+ {
154+ $ rawValue = $ string ->getAttribute (AttributeKey::RAW_VALUE );
155+ if (! is_string ($ rawValue )) {
156+ return false ;
157+ }
158+
159+ // any escape sequence other than \" makes the written content differ from the value
160+ return str_replace ('\\" ' , '" ' , substr ($ rawValue , 1 , -1 )) !== $ string ->value ;
161+ }
162+
163+ private function hasNonPrintableChars (string $ value ): bool
164+ {
165+ if (! StringUtils ::isMatch ($ value , self ::HAS_NON_PRINTABLE_CHARS )) {
166+ return false ;
167+ }
168+
169+ if (StringUtils ::isMatch ($ value , self ::CONTROL_CHARS_REGEX )) {
170+ return true ;
171+ }
172+
173+ // bytes above ASCII are printable as part of valid UTF-8 text, e.g. "é"
174+ return ! Validators ::isUnicode ($ value );
175+ }
140176}
0 commit comments