Skip to content

Commit

Permalink
Hotfix: correct array indicies when using ternary or coalesce ops
Browse files Browse the repository at this point in the history
Fixes #2694

I have find out that the issue is also when using coalesce operator.
Example, which is valid code, but has no sens would be:

```php
$array = [
    'foo' => 'foo',
    'bar' => $baz ? ['abc'] : ['def'],
    'hey' => $baz ?? ['one'] ?? ['two'],
];
```

Without fix we have 5 elements in `$indices` but we should have 3.

Added tests to cover changes.
  • Loading branch information
michalbundyra committed Nov 14, 2019
1 parent ed879f1 commit e6b37df
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/Sniffs/AbstractArraySniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,13 @@ public function process(File $phpcsFile, $stackPtr)
continue;
}

if ($tokens[$checkToken]['code'] === T_INLINE_THEN
|| $tokens[$checkToken]['code'] === T_COALESCE
) {
$checkToken = $phpcsFile->findEndOfStatement($checkToken);
continue;
}

if ($tokens[$checkToken]['code'] === T_ARRAY
|| $tokens[$checkToken]['code'] === T_OPEN_SHORT_ARRAY
|| $tokens[$checkToken]['code'] === T_CLOSURE
Expand Down
10 changes: 10 additions & 0 deletions src/Standards/Generic/Tests/Arrays/ArrayIndentUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,13 @@ $var = [
2 => 'two',
/* three */ 3 => 'three',
];

$array = [
'foo' => 'foo',
'bar' => $baz ?
['abc'] :
['def'],
'hey' => $baz ??
['one'] ??
['two'],
];
10 changes: 10 additions & 0 deletions src/Standards/Generic/Tests/Arrays/ArrayIndentUnitTest.inc.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,13 @@ $var = [
2 => 'two',
/* three */ 3 => 'three',
];

$array = [
'foo' => 'foo',
'bar' => $baz ?
['abc'] :
['def'],
'hey' => $baz ??
['one'] ??
['two'],
];
3 changes: 3 additions & 0 deletions src/Standards/Generic/Tests/Arrays/ArrayIndentUnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ public function getErrorList()
56 => 1,
57 => 1,
58 => 1,
61 => 1,
62 => 1,
65 => 1,
];

}//end getErrorList()
Expand Down

0 comments on commit e6b37df

Please sign in to comment.