Skip to content

Commit

Permalink
Report ?-> call on always-null
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed May 9, 2023
1 parent 411adf2 commit 74d1c9a
Show file tree
Hide file tree
Showing 6 changed files with 36 additions and 2 deletions.
4 changes: 4 additions & 0 deletions src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -1647,6 +1647,10 @@ private function lookForExpressionCallback(MutatingScope $scope, Expr $expr, Clo
private function ensureShallowNonNullability(MutatingScope $scope, Scope $originalScope, Expr $exprToSpecify): EnsuredNonNullabilityResult
{
$exprType = $scope->getType($exprToSpecify);
$isNull = $exprType->isNull();
if ($isNull->yes()) {
return new EnsuredNonNullabilityResult($scope, []);
}
$exprTypeWithoutNull = TypeCombinator::removeNull($exprType);
if ($exprType->equals($exprTypeWithoutNull)) {
$originalExprType = $originalScope->getType($exprToSpecify);
Expand Down
8 changes: 8 additions & 0 deletions tests/PHPStan/Rules/Methods/CallMethodsRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1742,6 +1742,14 @@ public function testNullSafe(): void
'Parameter #1 $passedByRef of method NullsafeMethodCall\Foo::doBaz() is passed by reference, so it expects variables only.',
27,
],
[
'Cannot call method foo() on null.',
33,
],
[
'Cannot call method foo() on null.',
34,
],
]);
}

Expand Down
7 changes: 7 additions & 0 deletions tests/PHPStan/Rules/Methods/data/nullsafe-method-call.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,11 @@ public function doLorem(?self $selfOrNull): void
$this->doBaz($selfOrNull?->test->test);
}

public function doNull(): void
{
$null = null;
$null->foo();
$null?->foo();
}

}
8 changes: 8 additions & 0 deletions tests/PHPStan/Rules/Properties/AccessPropertiesRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,14 @@ public function testNullSafe(): void
'Cannot access property $bar on string.',
22,
],
[
'Cannot access property $foo on null.',
28,
],
[
'Cannot access property $foo on null.',
29,
],
]);
}

Expand Down
4 changes: 2 additions & 2 deletions tests/PHPStan/Rules/Properties/data/bug-4559.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@

class HelloWorld
{
public function doBar()
public function doBar(string $s)
{
$response = json_decode('');
$response = json_decode($s);
if (isset($response->error->code)) {
echo $response->error->message ?? '';
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,11 @@ public function doBar(string $string, ?string $nullableString): void
echo $nullableString?->bar ?? 4;
}

public function doNull(): void
{
$null = null;
$null->foo;
$null?->foo;
}

}

0 comments on commit 74d1c9a

Please sign in to comment.