Skip to content

Commit 71df85c

Browse files
committed
getTokensAsString() method: Add option to respect original content
When a file uses tabs and a `tab-width` is set, the `content` will have spaces instead of tabs. This could lead to situations where the output of `getTokensAsString()` when used to move content about would unintentionally replace tabs with spaces. This small change allows for retrieving the original content by passing a third parameter. I've chosen to add a parameter rather than change the default function behaviour to prevent breaks for existing sniffs relying on this behaviour, like the Squiz/ArrayDeclaration sniff: https://github.com/squizlabs/PHP_CodeSniffer/blob/2ca6cf56420616cb47a88249eb5e3520f0e31ac7/src/Standards/Squiz/Sniffs/Arrays/ArrayDeclarationSniff.php#L477-L480
1 parent 2ca6cf5 commit 71df85c

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/Files/File.php

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1679,12 +1679,14 @@ public function isReference($stackPtr)
16791679
* Returns the content of the tokens from the specified start position in
16801680
* the token stack for the specified length.
16811681
*
1682-
* @param int $start The position to start from in the token stack.
1683-
* @param int $length The length of tokens to traverse from the start pos.
1682+
* @param int $start The position to start from in the token stack.
1683+
* @param int $length The length of tokens to traverse from the start pos.
1684+
* @param int $origContent Whether the original content or the tab replaced
1685+
* content should be used.
16841686
*
16851687
* @return string The token contents.
16861688
*/
1687-
public function getTokensAsString($start, $length)
1689+
public function getTokensAsString($start, $length, $origContent=false)
16881690
{
16891691
$str = '';
16901692
$end = ($start + $length);
@@ -1693,7 +1695,13 @@ public function getTokensAsString($start, $length)
16931695
}
16941696

16951697
for ($i = $start; $i < $end; $i++) {
1696-
$str .= $this->tokens[$i]['content'];
1698+
// If tabs are being converted to spaces by the tokeniser, the
1699+
// original content should be used instead of the converted content.
1700+
if ($origContent === true && isset($this->tokens[$i]['orig_content']) === true) {
1701+
$str .= $this->tokens[$i]['orig_content'];
1702+
} else {
1703+
$str .= $this->tokens[$i]['content'];
1704+
}
16971705
}
16981706

16991707
return $str;

0 commit comments

Comments
 (0)