Browse Source

NonPrintableCharacterFixer - fix for when removing non-printable character break PHP syntax

Kuba Werłos 3 years ago
parent
commit
940690d80a

+ 13 - 1
src/Fixer/Basic/NonPrintableCharacterFixer.php

@@ -174,7 +174,19 @@ final class NonPrintableCharacterFixer extends AbstractFixer implements Configur
             }
 
             if ($token->isGivenKind(self::$tokens)) {
-                $tokens[$index] = new Token([$token->getId(), strtr($content, $replacements)]);
+                $newContent = strtr($content, $replacements);
+
+                // variable name cannot contain space
+                if ($token->isGivenKind([T_STRING_VARNAME, T_VARIABLE]) && str_contains($newContent, ' ')) {
+                    continue;
+                }
+
+                // multiline comment must have "*/" only at the end
+                if ($token->isGivenKind([T_COMMENT, T_DOC_COMMENT]) && str_starts_with($newContent, '/*') && strpos($newContent, '*/') !== \strlen($newContent) - 2) {
+                    continue;
+                }
+
+                $tokens[$index] = new Token([$token->getId(), $newContent]);
             }
         }
     }

+ 12 - 0
tests/Fixer/Basic/NonPrintableCharacterFixerTest.php

@@ -103,6 +103,18 @@ echo "Hello'.pack('H*', 'e280af').'World'.pack('H*', 'c2a0').'!";',
                 '<?php echo \'12345\';?>abc<?php ?>',
                 '<?php echo \'123'.pack('H*', 'e2808b').'45\';?>a'.pack('H*', 'e2808b').'bc<?php ?>',
             ],
+            [
+                '<?php echo "${foo'.pack('H*', 'c2a0').'bar} is great!";',
+            ],
+            [
+                '<?php echo $foo'.pack('H*', 'c2a0').'bar;',
+            ],
+            [
+                '<?php /* foo *'.pack('H*', 'e2808b').'/ bar */',
+            ],
+            [
+                '<?php /** foo *'.pack('H*', 'e2808b').'/ bar */',
+            ],
         ];
     }