Skip to content

Commit

Permalink
Enter assignment of property fetch's var when in null coalesce operator
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Sep 11, 2021
1 parent 165504c commit 7ddfa17
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -2326,8 +2326,14 @@ static function () use ($expr, $rightResult): MutatingScope {
} elseif ($expr instanceof Coalesce) {
$nonNullabilityResult = $this->ensureNonNullability($scope, $expr->left, false);

if ($expr->left instanceof PropertyFetch || $expr->left instanceof StaticPropertyFetch || $expr->left instanceof Expr\NullsafePropertyFetch) {
$scope = $nonNullabilityResult->getScope();
if ($expr->left instanceof PropertyFetch || $expr->left instanceof Expr\NullsafePropertyFetch) {
$scope = $this->lookForEnterVariableAssign($nonNullabilityResult->getScope(), $expr->left->var);
} elseif ($expr->left instanceof StaticPropertyFetch) {
if ($expr->left->class instanceof Expr) {
$scope = $this->lookForEnterVariableAssign($nonNullabilityResult->getScope(), $expr->left->class);
} else {
$scope = $nonNullabilityResult->getScope();
}
} else {
$scope = $this->lookForEnterVariableAssign($nonNullabilityResult->getScope(), $expr->left);
}
Expand Down
10 changes: 10 additions & 0 deletions tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -840,4 +840,14 @@ public function testBug4412(): void
]);
}

public function testBug3283(): void
{
$this->cliArgumentsVariablesRegistered = true;
$this->polluteScopeWithLoopInitialAssignments = false;
$this->polluteCatchScopeWithTryAssignments = false;
$this->checkMaybeUndefinedVariables = true;
$this->polluteScopeWithAlwaysIterableForeach = true;
$this->analyse([__DIR__ . '/data/bug-3283.php'], []);
}

}
15 changes: 15 additions & 0 deletions tests/PHPStan/Rules/Variables/data/bug-3283.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Bug3283;

function (): void
{
$test = random_int(0, 10);

if ($test > 5) {
$user = new \stdClass;
$user->name = 'Thibaud';
}

echo $user->name ?? 'Default';
};

0 comments on commit 7ddfa17

Please sign in to comment.