From 08bf101f48f811cd41e6ea7eb50123c30757404f Mon Sep 17 00:00:00 2001 From: Brown Date: Thu, 2 May 2019 17:21:02 -0400 Subject: [PATCH] Fix #1598, catching unused variables followed by try inside loop --- .../Analyzer/Statements/Block/TryAnalyzer.php | 2 +- tests/UnusedCodeTest.php | 2 +- tests/UnusedVariableTest.php | 11 +++++++++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/Psalm/Internal/Analyzer/Statements/Block/TryAnalyzer.php b/src/Psalm/Internal/Analyzer/Statements/Block/TryAnalyzer.php index 3c528fd3a..6f28b9ec0 100644 --- a/src/Psalm/Internal/Analyzer/Statements/Block/TryAnalyzer.php +++ b/src/Psalm/Internal/Analyzer/Statements/Block/TryAnalyzer.php @@ -342,7 +342,7 @@ class TryAnalyzer if ($catch_actions[$i] !== [ScopeAnalyzer::ACTION_END]) { foreach ($catch_context->vars_in_scope as $var_id => $type) { - if ($context->hasVariable($var_id) + if (isset($context->vars_in_scope[$var_id]) && $context->vars_in_scope[$var_id]->getId() !== $type->getId() ) { $context->vars_in_scope[$var_id] = Type::combineUnionTypes( diff --git a/tests/UnusedCodeTest.php b/tests/UnusedCodeTest.php index 7dbb79b52..0499eb1e3 100644 --- a/tests/UnusedCodeTest.php +++ b/tests/UnusedCodeTest.php @@ -294,7 +294,7 @@ class UnusedCodeTest extends TestCase public function bar() : void { $c = $this->getC(); - foreach ([1, 2, 3] as $i) { + foreach ([1, 2, 3] as $_) { try { $c->foo(); } catch (Exception $e) {} diff --git a/tests/UnusedVariableTest.php b/tests/UnusedVariableTest.php index 3c855359a..ac4e61cf5 100644 --- a/tests/UnusedVariableTest.php +++ b/tests/UnusedVariableTest.php @@ -1427,6 +1427,17 @@ class UnusedVariableTest extends TestCase }', 'error_message' => 'UnusedVariable', ], + 'detectUnusedVarBeforeTryInsideForeach' => [ + ' 'UnusedVariable', + ], ]; } }