From 49b84946bcef41d982e3e6a05b25e24cfad20f19 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Mon, 29 Jul 2024 21:27:21 +0200 Subject: [PATCH] AbstractPatternSniff: prevent PHP notice In a live coding situation, the token triggering the pattern being looked for could be at or near the end of the file. This could lead to a situation where the pattern could never match anyhow as there are not enough tokens left in the file to match against. In this situation, the sniff could trigger the following PHP error: ``` Increment on type bool has no effect, this will change in the next major version of PHP in path/to/phpcs/src/Sniffs/AbstractPatternSniff.php on line 627 ``` This commit prevents this error by bowing out early if there are not enough tokens in the file under scan to match the pattern. Tested via the `Squiz.Functions.FunctionDeclaration` sniff via which this issue was discovered. --- src/Sniffs/AbstractPatternSniff.php | 5 +++++ .../Squiz/Tests/Functions/FunctionDeclarationUnitTest.2.inc | 5 +++++ .../Squiz/Tests/Functions/FunctionDeclarationUnitTest.3.inc | 5 +++++ 3 files changed, 15 insertions(+) create mode 100644 src/Standards/Squiz/Tests/Functions/FunctionDeclarationUnitTest.2.inc create mode 100644 src/Standards/Squiz/Tests/Functions/FunctionDeclarationUnitTest.3.inc diff --git a/src/Sniffs/AbstractPatternSniff.php b/src/Sniffs/AbstractPatternSniff.php index e895365688..d9528dccf8 100644 --- a/src/Sniffs/AbstractPatternSniff.php +++ b/src/Sniffs/AbstractPatternSniff.php @@ -416,6 +416,11 @@ protected function processPattern($patternInfo, File $phpcsFile, $stackPtr) $lastAddedStackPtr = null; $patternLen = count($pattern); + if (($stackPtr + $patternLen - $patternInfo['listen_pos']) > $phpcsFile->numTokens) { + // Pattern can never match as there are not enough tokens left in the file. + return false; + } + for ($i = $patternInfo['listen_pos']; $i < $patternLen; $i++) { if (isset($tokens[$stackPtr]) === false) { break; diff --git a/src/Standards/Squiz/Tests/Functions/FunctionDeclarationUnitTest.2.inc b/src/Standards/Squiz/Tests/Functions/FunctionDeclarationUnitTest.2.inc new file mode 100644 index 0000000000..51a55e92ad --- /dev/null +++ b/src/Standards/Squiz/Tests/Functions/FunctionDeclarationUnitTest.2.inc @@ -0,0 +1,5 @@ +