-
-
Notifications
You must be signed in to change notification settings - Fork 930
Description
Bug report
PHPStan seems to not be inferring a narrowing of a type for an array value if that value's type is narrowed by accessing a key that is not a simple variable (arithmetic expression, and backed enum ->value
are the ones I checked).
The code snippet attached employs a (somewhat unusual, for sure, but simple) Fibonacci sequence memoization strategy, by preparing a zero-indexed memoization array with null values when instantiated. Both fib1
and fib0
always return int
.
- When using
fib1
the access to the memoization array is done by decrementing the parameter by one (i.e. an expression):$this->mem[$n - 1]
. It is guaranteed to have a return value type ofint
, however areturn.type
error is reported, stating that the type of$this->mem[$n - 1]
isint|null
. - When using
fib0
(the zero-indexed counterpart tofib1
), the access to the memoization array is made using the given parameter (a simple variable) as key,$this->mem[$n]
. In this form, PHPStan correctly infers the narrowing of the variable, and does not report any error.
Code snippet that reproduces the problem
https://phpstan.org/r/a685005a-94c9-45e2-a9b0-52f924e2d3e9
Expected output
The narrowing of types should hold for expression keys that always evaluate to the same value, such as arithmetic expressions with literals, or a backed enum's ->value
(and possibly others).
Specifically, in the case of the code snippet, fib1
should not report a return.type
error (much like fib0
).
Did PHPStan help you today? Did it make you happy in any way?
PHPStan is awesome! It makes developing with PHP a much less frustrating experience. Thank you!