Skip to content

Commit e536947

Browse files
committed
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.
1 parent 68a654f commit e536947

File tree

3 files changed

+15
-0
lines changed

3 files changed

+15
-0
lines changed

src/Sniffs/AbstractPatternSniff.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,11 @@ protected function processPattern($patternInfo, File $phpcsFile, $stackPtr)
416416
$lastAddedStackPtr = null;
417417
$patternLen = count($pattern);
418418

419+
if (($stackPtr + $patternLen - $patternInfo['listen_pos']) > $phpcsFile->numTokens) {
420+
// Pattern can never match as there are not enough tokens left in the file.
421+
return false;
422+
}
423+
419424
for ($i = $patternInfo['listen_pos']; $i < $patternLen; $i++) {
420425
if (isset($tokens[$stackPtr]) === false) {
421426
break;
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+
function
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+
function // Comment.

0 commit comments

Comments
 (0)