From d4ce6f601b5640302fedae3a3d981e52eb832b44 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Mon, 10 Jul 2023 15:24:38 +0200 Subject: [PATCH] Arrays::getDoubleArrowPtr(): allow for (keyed) lists in array values PHP 7.2 introduced keyed lists, but the `Arrays::getDoubleArrowPtr()` method did not take this into account correctly. Keyed short lists were already handled correctly as they tokenize the same as short arrays. Keyed long lists were not. Fixed now. Includes tests. --- PHPCSUtils/Utils/Arrays.php | 9 +++++++++ Tests/Utils/Arrays/GetDoubleArrowPtrTest.inc | 6 ++++++ Tests/Utils/Arrays/GetDoubleArrowPtrTest.php | 10 ++++++++++ 3 files changed, 25 insertions(+) diff --git a/PHPCSUtils/Utils/Arrays.php b/PHPCSUtils/Utils/Arrays.php index ce321b04..3fe7a100 100644 --- a/PHPCSUtils/Utils/Arrays.php +++ b/PHPCSUtils/Utils/Arrays.php @@ -39,6 +39,7 @@ final class Arrays \T_OPEN_SHORT_ARRAY => \T_OPEN_SHORT_ARRAY, // Inline function, control structures and other things to skip over. + \T_LIST => \T_LIST, \T_FN => \T_FN, \T_MATCH => \T_MATCH, \T_ATTRIBUTE => \T_ATTRIBUTE, @@ -208,6 +209,14 @@ public static function getDoubleArrowPtr(File $phpcsFile, $start, $end) continue; } + // Skip over potentially keyed long lists. + if ($tokens[$doubleArrow]['code'] === \T_LIST + && isset($tokens[$doubleArrow]['parenthesis_closer']) + ) { + $doubleArrow = $tokens[$doubleArrow]['parenthesis_closer']; + continue; + } + // Start of nested long/short array. break; } while ($doubleArrow < $end); diff --git a/Tests/Utils/Arrays/GetDoubleArrowPtrTest.inc b/Tests/Utils/Arrays/GetDoubleArrowPtrTest.inc index c0e6a866..ce5a865b 100644 --- a/Tests/Utils/Arrays/GetDoubleArrowPtrTest.inc +++ b/Tests/Utils/Arrays/GetDoubleArrowPtrTest.inc @@ -104,6 +104,12 @@ $array = [ FOO => BAR, default => [0 => 10], } => 'value', + + /* testNoArrowKeyedLongListInValue */ + list( 'key1' => $a, 'key2' => $b ) = $array, + + /* testNoArrowKeyedShortListInValue */ + [ 'key1' => $a, 'key2' => $b ] = $array, /* testNoArrowValueClosureWithAttribute */ #[MyAttribute([0 => 'value'])] function() { /* do something */ }(), diff --git a/Tests/Utils/Arrays/GetDoubleArrowPtrTest.php b/Tests/Utils/Arrays/GetDoubleArrowPtrTest.php index d0057d16..a0785fc2 100644 --- a/Tests/Utils/Arrays/GetDoubleArrowPtrTest.php +++ b/Tests/Utils/Arrays/GetDoubleArrowPtrTest.php @@ -234,6 +234,16 @@ public static function dataGetDoubleArrowPtr() 'expected' => 38, ], + // Safeguard that PHP 7.2 keyed lists in values are handled correctly. + 'test-no-arrow-value-keyed-long-list' => [ + 'testMarker' => '/* testNoArrowKeyedLongListInValue */', + 'expected' => false, + ], + 'test-no-arrow-value-keyed-short-list' => [ + 'testMarker' => '/* testNoArrowKeyedShortListInValue */', + 'expected' => false, + ], + // Safeguard that double arrows in PHP 8.0 attributes are disregarded. 'test-no-arrow-value-closure-with-attached-attribute-containing-arrow' => [ 'testMarker' => '/* testNoArrowValueClosureWithAttribute */',