Skip to content

Commit

Permalink
NullsafeMethodCall makes the variable not null for the rest of the sc…
Browse files Browse the repository at this point in the history
…ope (#5771)
  • Loading branch information
orklah committed May 14, 2021
1 parent 0b96f40 commit 1bb4a05
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,25 @@ public static function scrapeAssertions(
);
}

//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
|| $conditional instanceof PhpParser\Node\Expr\BinaryOp\GreaterOrEqual
) {
Expand Down
33 changes: 33 additions & 0 deletions tests/TypeReconciliation/TypeAlgebraTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1077,6 +1077,22 @@ function foo(?string $c): string {
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',
],
];
}

Expand Down Expand Up @@ -1321,6 +1337,23 @@ function takesA(?A $a) : void {
}',
'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',
],
];
}
}

0 comments on commit 1bb4a05

Please sign in to comment.