From be494bf51434a1a079ddc676774f8143a6fadec5 Mon Sep 17 00:00:00 2001 From: Rodrigo Primo Date: Thu, 4 Jan 2024 11:32:56 -0300 Subject: [PATCH] Generic/ForLoopShouldBeWhileLoop: fix E_DEPRECATED error This commit fixes an issue in the sniff that could result in the following E_DEPRECATED error when running PHP 8.3: ``` Decrement on type null has no effect, this will change in the next major version of PHP src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopShouldBeWhileLoopSniff.php:65 ``` This sniff relies on finding the position of the open and closing parentheses for a given `for` loop. However, the problem was that there was no defensive code for cases when the closing parenthesis is missing. The sniff would still work when running PHP >= 8.2, but on PHP 8.3 it would throw the deprecated message above. This would happen because since there is no closing parenthesis `$end` is set to null, and $next <= $end always evaluates to false (https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/84acf4e56f110db8e75cb9a575c5727df637643c/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopShouldBeWhileLoopSniff.php#L74). The issue was fixed by bailing early if the closing parenthesis is missing. A test with a `for` loop without the closing parenthesis was added. --- .../Sniffs/CodeAnalysis/ForLoopShouldBeWhileLoopSniff.php | 2 +- .../Tests/CodeAnalysis/ForLoopShouldBeWhileLoopUnitTest.3.inc | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 src/Standards/Generic/Tests/CodeAnalysis/ForLoopShouldBeWhileLoopUnitTest.3.inc diff --git a/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopShouldBeWhileLoopSniff.php b/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopShouldBeWhileLoopSniff.php index 286ce62704..4a1d7a09db 100644 --- a/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopShouldBeWhileLoopSniff.php +++ b/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopShouldBeWhileLoopSniff.php @@ -57,7 +57,7 @@ public function process(File $phpcsFile, $stackPtr) $token = $tokens[$stackPtr]; // Skip invalid statement. - if (isset($token['parenthesis_opener']) === false) { + if (isset($token['parenthesis_opener']) === false || isset($token['parenthesis_closer']) === false) { return; } diff --git a/src/Standards/Generic/Tests/CodeAnalysis/ForLoopShouldBeWhileLoopUnitTest.3.inc b/src/Standards/Generic/Tests/CodeAnalysis/ForLoopShouldBeWhileLoopUnitTest.3.inc new file mode 100644 index 0000000000..543901d937 --- /dev/null +++ b/src/Standards/Generic/Tests/CodeAnalysis/ForLoopShouldBeWhileLoopUnitTest.3.inc @@ -0,0 +1,4 @@ +