Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AbstractArrayDeclarationSniff::getActualArrayKey(): improve handling of escaped embedded vars #379

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,7 @@ public function getActualArrayKey(File $phpcsFile, $startPtr, $endPtr)
$text = TextStrings::getCompleteTextString($phpcsFile, $i);

// Check if there's a variable in the heredoc.
if (\preg_match('`(?<![\\\\])\$`', $text) === 1) {
if ($text !== TextStrings::stripEmbeds($text)) {
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ my $var text
EOD
=> 'excluded',
$var['key']{1} => 'excluded',
<<<EOD
my complex {${getName()}} text
EOD
=> 'excluded',
<<<EOD
$var text
EOD
=> 'excluded',
];

/* testAllEmptyString */
Expand Down Expand Up @@ -112,3 +120,19 @@ NOW
=> 6,
"abc" => 7,
];

/* testHeredocWithEscapedVarInKey */
$heredocStringKeyWithEscapedVar = [
<<<EOD
a{\$b}c
EOD
=> 1,
<<<EOD
a\$bc
EOD
=> 2,
<<<EOD
$\{abc}
EOD
=> 3,
];
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,38 @@ public function dataGetActualArrayKey()
],
];
}

/**
* Test retrieving the actual array key from a heredoc when the key could contain interpolation, but doesn't,
* as the interpolation is escaped.
*
* @return void
*/
public function testGetActualArrayKeyFromHeredocWithEscapedVarInKey()
{
$testObj = new ArrayDeclarationSniffTestDouble();
$testObj->tokens = self::$phpcsFile->getTokens();

$stackPtr = $this->getTargetToken('/* testHeredocWithEscapedVarInKey */', [\T_ARRAY, \T_OPEN_SHORT_ARRAY]);
$arrayItems = PassedParameters::getParameters(self::$phpcsFile, $stackPtr);

$expected = [
1 => 'a{$b}c',
2 => 'a$bc',
3 => '$\{abc}',
];

$this->assertCount(\count($expected), $arrayItems);

foreach ($arrayItems as $itemNr => $arrayItem) {
$arrowPtr = Arrays::getDoubleArrowPtr(self::$phpcsFile, $arrayItem['start'], $arrayItem['end']);
$result = $testObj->getActualArrayKey(self::$phpcsFile, $arrayItem['start'], ($arrowPtr - 1));
$this->assertSame(
$expected[$itemNr],
$result,
'Failed: actual key ' . $result . ' is not the same as the expected key ' . $expected[$itemNr]
. ' for item number ' . $itemNr
);
}
}
}