Skip to content

Commit 7a4c787

Browse files
committed
Squiz/OperatorBracket: prevent PHP notices during live coding
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.
1 parent db1a142 commit 7a4c787

File tree

3 files changed

+24
-5
lines changed

3 files changed

+24
-5
lines changed

src/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -354,16 +354,23 @@ public function addMissingBracketsError($phpcsFile, $stackPtr)
354354
}
355355

356356
if ($tokens[$after]['code'] === T_OPEN_PARENTHESIS) {
357+
if (isset($tokens[$after]['parenthesis_closer']) === false) {
358+
// Live coding/parse error. Ignore.
359+
return;
360+
}
361+
357362
$after = $tokens[$after]['parenthesis_closer'];
358363
continue;
359364
}
360365

361-
if ($tokens[$after]['code'] === T_OPEN_SQUARE_BRACKET) {
362-
$after = $tokens[$after]['bracket_closer'];
363-
continue;
364-
}
366+
if (($tokens[$after]['code'] === T_OPEN_SQUARE_BRACKET
367+
|| $tokens[$after]['code'] === T_OPEN_SHORT_ARRAY)
368+
) {
369+
if (isset($tokens[$after]['bracket_closer']) === false) {
370+
// Live coding/parse error. Ignore.
371+
return;
372+
}
365373

366-
if ($tokens[$after]['code'] === T_OPEN_SHORT_ARRAY) {
367374
$after = $tokens[$after]['bracket_closer'];
368375
continue;
369376
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<?php
2+
3+
// Intentional parse error. This has to be the last (and only) test in the file.
4+
// Live coding test. The sniff should stay silent.
5+
class ParseErrors {
6+
const A|(B PARSE_ERROR = null;
7+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<?php
2+
3+
// Intentional parse error. This has to be the last (and only) test in the file.
4+
// Live coding test. The sniff should stay silent.
5+
$a = [10, 20] + [

0 commit comments

Comments
 (0)