From e7f28ccca0316709318ad151b347dc24e30c9d21 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 18 Oct 2022 13:24:06 +0200 Subject: [PATCH] AbstractArrayDeclarationSniff::getActualArrayKey(): improve handling of escaped embedded vars ... in heredocs by using the new `TextStrings::stripEmbeds()` method. Includes additional tests. --- .../AbstractArrayDeclarationSniff.php | 2 +- .../GetActualArrayKeyTest.inc | 24 +++++++++++++ .../GetActualArrayKeyTest.php | 34 +++++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/PHPCSUtils/AbstractSniffs/AbstractArrayDeclarationSniff.php b/PHPCSUtils/AbstractSniffs/AbstractArrayDeclarationSniff.php index 91025e0c..809a026c 100644 --- a/PHPCSUtils/AbstractSniffs/AbstractArrayDeclarationSniff.php +++ b/PHPCSUtils/AbstractSniffs/AbstractArrayDeclarationSniff.php @@ -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('`(? 'excluded', $var['key']{1} => 'excluded', + << 'excluded', + << 'excluded', ]; /* testAllEmptyString */ @@ -112,3 +120,19 @@ NOW => 6, "abc" => 7, ]; + +/* testHeredocWithEscapedVarInKey */ +$heredocStringKeyWithEscapedVar = [ + << 1, + << 2, + << 3, +]; diff --git a/Tests/AbstractSniffs/AbstractArrayDeclaration/GetActualArrayKeyTest.php b/Tests/AbstractSniffs/AbstractArrayDeclaration/GetActualArrayKeyTest.php index 725c91d9..ed3b2fe4 100644 --- a/Tests/AbstractSniffs/AbstractArrayDeclaration/GetActualArrayKeyTest.php +++ b/Tests/AbstractSniffs/AbstractArrayDeclaration/GetActualArrayKeyTest.php @@ -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 + ); + } + } }