Skip to content

Commit

Permalink
Fix variable certainty after exhaustive switch
Browse files Browse the repository at this point in the history
  • Loading branch information
Richard van Velzen authored and ondrejmirtes committed Jul 28, 2022
1 parent 6478c73 commit e36e22c
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -1160,7 +1160,9 @@ private function processStmtNode(
}
}

if (!$hasDefaultCase) {
$exhaustive = $scopeForBranches->getType($stmt->cond) instanceof NeverType;

if (!$hasDefaultCase && !$exhaustive) {
$alwaysTerminating = false;
}

Expand All @@ -1169,7 +1171,7 @@ private function processStmtNode(
$alwaysTerminating = $alwaysTerminating && $branchFinalScopeResult->isAlwaysTerminating();
}

if (!$hasDefaultCase || $finalScope === null) {
if ((!$hasDefaultCase && !$exhaustive) || $finalScope === null) {
$finalScope = $scope->mergeWith($finalScope);
}

Expand Down
9 changes: 9 additions & 0 deletions tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -854,4 +854,13 @@ public function testBug3601(): void
$this->analyse([__DIR__ . '/data/bug-3601.php'], []);
}

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

}
21 changes: 21 additions & 0 deletions tests/PHPStan/Rules/Variables/data/bug-1016.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php declare(strict_types=1);

namespace Bug1016;

function () {
foreach ([1, 2, 3] as $i) {
switch ($i) {
case 1:
$a = "hello";
break;
case 2:
$a = "goodbye";
break;
case 3:
$a = "hello again";
break;
}

echo $a;
}
};

0 comments on commit e36e22c

Please sign in to comment.