phpstan-src icon indicating copy to clipboard operation
phpstan-src copied to clipboard

Fix non-existent offset when guarding

Open SplotyCode opened this issue 2 months ago • 1 comments

This pr is trying to fix a false positive.

/**
 * @param list<int> $array
 * @param positive-int $index
 */
public function guardNotSafeLowerBound(array $array, int $index) {
    if ($index < count($array)) { // index is within 0..count(array)-1
        return $array[$index]; // phpstan reports a potentially unsafe array access
    }
    return null;
}

Note that 1) $array is a list 2) $index is positive (or at least >= 0)

SplotyCode avatar Nov 08 '25 15:11 SplotyCode

There seems to be a regression

$var = null;
if ($index < count($array) {
    $var = 2;
}
if ($index < count($array) {
    /* phpstan does not recognize that $var is always 2 now */
}

This did work before this pr. I am wondering if this is also true for the other checks in the method i changed.

SplotyCode avatar Nov 11 '25 11:11 SplotyCode