Skip to content

Commit

Permalink
Squiz/OperatorBracket: prevent PHP notices during live coding
Browse files Browse the repository at this point in the history
During live coding (or in the case of parse errors), the "end of the expression" cannot always be correctly determined. In such a case, the sniff should stay silent.

This wasn't always handled correctly so far and could lead to the following PHP notices:
```
Undefined array key "parenthesis_closer" in path/to/phpcs/src/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php on line 357
Undefined array key "bracket_closer" in path/to/phpcs/src/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php on line 362
```

This commit fixes these by adding some extra defensive coding and bowing out when an unclosed bracket set is encountered.

Includes tests.
  • Loading branch information
jrfnl committed Jul 29, 2024
1 parent 080747b commit e667042
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -354,16 +354,23 @@ public function addMissingBracketsError($phpcsFile, $stackPtr)
}

if ($tokens[$after]['code'] === T_OPEN_PARENTHESIS) {
if (isset($tokens[$after]['parenthesis_closer']) === false) {
// Live coding/parse error. Ignore.
return;
}

$after = $tokens[$after]['parenthesis_closer'];
continue;
}

if ($tokens[$after]['code'] === T_OPEN_SQUARE_BRACKET) {
$after = $tokens[$after]['bracket_closer'];
continue;
}
if (($tokens[$after]['code'] === T_OPEN_SQUARE_BRACKET
|| $tokens[$after]['code'] === T_OPEN_SHORT_ARRAY)
) {
if (isset($tokens[$after]['bracket_closer']) === false) {
// Live coding/parse error. Ignore.
return;
}

if ($tokens[$after]['code'] === T_OPEN_SHORT_ARRAY) {
$after = $tokens[$after]['bracket_closer'];
continue;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

// Intentional parse error. This has to be the last (and only) test in the file.
// Live coding test. The sniff should stay silent.
class ParseErrors {
const A|(B PARSE_ERROR = null;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

// Intentional parse error. This has to be the last (and only) test in the file.
// Live coding test. The sniff should stay silent.
$a = [10, 20] + [

0 comments on commit e667042

Please sign in to comment.