Skip to content

Commit 7f4fdc7

Browse files
committed
Generic/UnnecessaryHeredoc: bug fix - stray backslashes after fixing
If the original heredoc contained an escaped variable or an escaped backslash (neither of which need heredoc), the nowdoc version of the text string would contain stray backslashes as these escapes are not needed in nowdocs, so would be interpreted as literals. Fixed now. Includes tests.
1 parent 6292af2 commit 7f4fdc7

File tree

5 files changed

+18
-6
lines changed

5 files changed

+18
-6
lines changed

src/Standards/Generic/Sniffs/Strings/UnnecessaryHeredocSniff.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,10 +85,22 @@ public function process(File $phpcsFile, $stackPtr)
8585

8686
$fix = $phpcsFile->addFixableWarning($warning, $stackPtr, 'Found');
8787
if ($fix === true) {
88+
$phpcsFile->fixer->beginChangeset();
89+
8890
$identifier = trim(ltrim($tokens[$stackPtr]['content'], '<'));
8991
$replaceWith = "'".trim($identifier, '"')."'";
9092
$replacement = str_replace($identifier, $replaceWith, $tokens[$stackPtr]['content']);
9193
$phpcsFile->fixer->replaceToken($stackPtr, $replacement);
94+
95+
for ($i = ($stackPtr + 1); $i < $closer; $i++) {
96+
$content = $tokens[$i]['content'];
97+
$content = str_replace(['\\$', '\\\\'], ['$', '\\'], $content);
98+
if ($tokens[$i]['content'] !== $content) {
99+
$phpcsFile->fixer->replaceToken($i, $content);
100+
}
101+
}
102+
103+
$phpcsFile->fixer->endChangeset();
92104
}
93105

94106
}//end process()

src/Standards/Generic/Tests/Strings/UnnecessaryHeredocUnitTest.1.inc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,5 +104,5 @@ END;
104104
$heredoc = <<< "END"
105105
some text
106106
some \$text
107-
some text
107+
some text \\ including a backslash
108108
END;

src/Standards/Generic/Tests/Strings/UnnecessaryHeredocUnitTest.1.inc.fixed

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,6 @@ END;
103103

104104
$heredoc = <<< 'END'
105105
some text
106-
some \$text
107-
some text
106+
some $text
107+
some text \ including a backslash
108108
END;

src/Standards/Generic/Tests/Strings/UnnecessaryHeredocUnitTest.2.inc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,5 +104,5 @@ $heredoc = <<<END
104104
$heredoc = <<< "END"
105105
some text
106106
some \$text
107-
some text
107+
some text \\ including a backslash
108108
END;

src/Standards/Generic/Tests/Strings/UnnecessaryHeredocUnitTest.2.inc.fixed

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,6 @@ $heredoc = <<<'END'
103103

104104
$heredoc = <<< 'END'
105105
some text
106-
some \$text
107-
some text
106+
some $text
107+
some text \ including a backslash
108108
END;

0 commit comments

Comments
 (0)