Skip to content

Commit

Permalink
AbstractPatternSniff: prevent PHP notice
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jrfnl committed Aug 1, 2024
1 parent 60a5557 commit 49b8494
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Sniffs/AbstractPatternSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

// Intentional parse error. This has to be the last (and only) test in the file.
// Live coding test. The sniff should stay silent.
function
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

// Intentional parse error. This has to be the last (and only) test in the file.
// Live coding test. The sniff should stay silent.
function // Comment.

0 comments on commit 49b8494

Please sign in to comment.