Skip to content

Commit

Permalink
Arrays::getDoubleArrowPtr(): allow for (keyed) lists in array values
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jrfnl committed Jul 10, 2023
1 parent 87630f9 commit d4ce6f6
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
9 changes: 9 additions & 0 deletions PHPCSUtils/Utils/Arrays.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down
6 changes: 6 additions & 0 deletions Tests/Utils/Arrays/GetDoubleArrowPtrTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -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 */ }(),
Expand Down
10 changes: 10 additions & 0 deletions Tests/Utils/Arrays/GetDoubleArrowPtrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 */',
Expand Down

0 comments on commit d4ce6f6

Please sign in to comment.