Skip to content

Commit 5a0379a

Browse files
committed
TextStrings::getCompleteTextString(): remove newline at end of heredoc/nowdoc
PHP itself does not include the last new line in a heredoc/nowdoc text string when handling it, so this method shouldn't either. Included adjusted unit tests.
1 parent 3c07fb6 commit 5a0379a

File tree

2 files changed

+19
-14
lines changed

2 files changed

+19
-14
lines changed

PHPCSUtils/Utils/TextStrings.php

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -62,17 +62,21 @@ public static function getCompleteTextString(File $phpcsFile, $stackPtr, $stripQ
6262
}
6363
}
6464

65+
$stripNewline = false;
66+
6567
switch ($tokens[$stackPtr]['code']) {
6668
case \T_START_HEREDOC:
67-
$stripQuotes = false;
68-
$targetType = \T_HEREDOC;
69-
$current = ($stackPtr + 1);
69+
$stripQuotes = false;
70+
$stripNewline = true;
71+
$targetType = \T_HEREDOC;
72+
$current = ($stackPtr + 1);
7073
break;
7174

7275
case \T_START_NOWDOC:
73-
$stripQuotes = false;
74-
$targetType = \T_NOWDOC;
75-
$current = ($stackPtr + 1);
76+
$stripQuotes = false;
77+
$stripNewline = true;
78+
$targetType = \T_NOWDOC;
79+
$current = ($stackPtr + 1);
7680
break;
7781

7882
default:
@@ -87,6 +91,11 @@ public static function getCompleteTextString(File $phpcsFile, $stackPtr, $stripQ
8791
++$current;
8892
} while (isset($tokens[$current]) && $tokens[$current]['code'] === $targetType);
8993

94+
if ($stripNewline === true) {
95+
// Heredoc/nowdoc: strip the new line at the end of the string to emulate how PHP sees the string.
96+
$string = rtrim($string, "\r\n");
97+
}
98+
9099
if ($stripQuotes === true) {
91100
return self::stripQuotes($string);
92101
}

Tests/Utils/TextStrings/GetCompleteTextStringTest.php

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -156,26 +156,22 @@ public function dataGetCompleteTextString()
156156
'first line
157157
second $line
158158
third line
159-
fourth line
160-
',
159+
fourth line',
161160
'first line
162161
second $line
163162
third line
164-
fourth line
165-
',
163+
fourth line',
166164
],
167165
'nowdoc' => [
168166
'/* testNowdocString */',
169167
'first line
170168
second line
171169
third line
172-
fourth line
173-
',
170+
fourth line',
174171
'first line
175172
second line
176173
third line
177-
fourth line
178-
',
174+
fourth line',
179175
],
180176
'text-string-at-end-of-file' => [
181177
'/* testTextStringAtEndOfFile */',

0 commit comments

Comments
 (0)