1
0
mirror of https://github.com/danog/psalm.git synced 2025-01-22 05:41:20 +01:00

NullsafeMethodCall makes the variable not null for the rest of the scope (#5771)

This commit is contained in:
orklah 2021-05-15 01:21:01 +02:00 committed by GitHub
parent 0b96f40198
commit 1bb4a05725
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 0 deletions

View File

@ -138,6 +138,25 @@ class AssertionFinder
); );
} }
//A nullsafe method call basically adds an assertion !null for the checked variable
if ($conditional instanceof PhpParser\Node\Expr\NullsafeMethodCall) {
$if_types = [];
$var_name = ExpressionIdentifier::getArrayVarId(
$conditional->var,
$this_class_name,
$source
);
if ($var_name) {
$if_types[$var_name] = [['!null']];
}
//we may throw a RedundantNullsafeMethodCall here in the future if $var_name is never null
return $if_types ? [$if_types] : [];
}
if ($conditional instanceof PhpParser\Node\Expr\BinaryOp\Greater if ($conditional instanceof PhpParser\Node\Expr\BinaryOp\Greater
|| $conditional instanceof PhpParser\Node\Expr\BinaryOp\GreaterOrEqual || $conditional instanceof PhpParser\Node\Expr\BinaryOp\GreaterOrEqual
) { ) {

View File

@ -1077,6 +1077,22 @@ class TypeAlgebraTest extends \Psalm\Tests\TestCase
return ""; return "";
}' }'
], ],
'notNullAfterSuccessfulNullsafeMethodCall' => [
'<?php
interface X {
public function a(): bool;
public function b(): string;
}
function foo(?X $x): void {
if ($x?->a()) {
echo $x->b();
}
}',
[],
[],
'8.1',
],
]; ];
} }
@ -1321,6 +1337,23 @@ class TypeAlgebraTest extends \Psalm\Tests\TestCase
}', }',
'error_message' => 'PossiblyNullReference', 'error_message' => 'PossiblyNullReference',
], ],
'stillNullAfterNullsafeMethodCall' => [
'<?php
interface X {
public function a(): bool;
public function b(): string;
}
function foo(?X $x): void {
if (!($x?->a())) {
echo $x->b();
}
}',
'error_message' => 'NullReference',
[],
false,
'8.1',
],
]; ];
} }
} }