From 7a4c7871528b3ad6e1d9a23937d887c5b4c3b7c2 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Mon, 29 Jul 2024 22:57:06 +0200 Subject: [PATCH] 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. --- .../Sniffs/Formatting/OperatorBracketSniff.php | 17 ++++++++++++----- .../Formatting/OperatorBracketUnitTest.2.inc | 7 +++++++ .../Formatting/OperatorBracketUnitTest.3.inc | 5 +++++ 3 files changed, 24 insertions(+), 5 deletions(-) create mode 100644 src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.2.inc create mode 100644 src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.3.inc diff --git a/src/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php b/src/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php index b79e6b3ec6..44429012a1 100644 --- a/src/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php +++ b/src/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php @@ -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; } diff --git a/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.2.inc b/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.2.inc new file mode 100644 index 0000000000..1284f121fc --- /dev/null +++ b/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.2.inc @@ -0,0 +1,7 @@ +