I have a function that checks if a value is null and after I call that function I use the value that is obviously not null.
but phpstan still says it could be null.
Do you guys have any solution for phpstan to know the outcome of this function.
protected ?string $filterCacheKey = null;
protected function usesFilterCaching(): bool
{
return $this->filterCacheKey !== null;
}
Parameter #1 $key of method IlluminateContractsSessionSession::get() expects string, string|null given.
if ($this->usesFilterCaching() && $this->request()->method() === Request::METHOD_GET) {
$sessionCacheFilters = $this->filterStore()->get($this->filterCacheKey);
return Arr::get($sessionCacheFilters, $filterName, $defaultChecked);
}
3
Answers
I think this is the cleanest solution:
I added the following docblock to the
usesFilterCaching()
function.This sets
$this->filterCacheKey
to a string if the function returns true.I think your problem is right here:
$this->filterStore()
does not have a value at key$this->filterCacheKey
So I think your check should be:
if ($this->usesFilterCaching() && $this->filterStore()->get($this->filterCacheKey) != null && $this->request()->method() === Request::METHOD_GET)
Although your code is clearly checking the null value before it is used, phpstan does not check called methods. It is a static analysis tool that will only stick to parameter types and return types, not what checks occur inside a called function.
As a quick workaround for this problem, I would suggest removing the
usesFilterCaching
function altogether as it can be replaced with a simple if check like so:This will perform the same null check and the code will not be executed if the variable is null.