diff --git a/src/Psalm/Context.php b/src/Psalm/Context.php index f62616160..6a8af0cd0 100644 --- a/src/Psalm/Context.php +++ b/src/Psalm/Context.php @@ -630,6 +630,10 @@ class Context } } + /** + * This method is used after assignments to variables to remove any existing + * items in $vars_in_scope that are now made redundant by an update to some data + */ public function removeDescendents( string $remove_var_id, ?Union $existing_type = null, diff --git a/src/Psalm/Internal/Analyzer/Statements/Block/TryAnalyzer.php b/src/Psalm/Internal/Analyzer/Statements/Block/TryAnalyzer.php index 58399df1a..b5c1424b5 100644 --- a/src/Psalm/Internal/Analyzer/Statements/Block/TryAnalyzer.php +++ b/src/Psalm/Internal/Analyzer/Statements/Block/TryAnalyzer.php @@ -306,6 +306,14 @@ class TryAnalyzer ) ); + // removes dependent vars from $context + $catch_context->removeDescendents( + $catch_var_id, + null, + $catch_context->vars_in_scope[$catch_var_id], + $statements_analyzer + ); + $catch_context->vars_possibly_in_scope[$catch_var_id] = true; $location = new CodeLocation($statements_analyzer->getSource(), $catch->var); diff --git a/tests/Template/FunctionTemplateAssertTest.php b/tests/Template/FunctionTemplateAssertTest.php index 00613e89b..eab898d6b 100644 --- a/tests/Template/FunctionTemplateAssertTest.php +++ b/tests/Template/FunctionTemplateAssertTest.php @@ -732,6 +732,41 @@ class FunctionTemplateAssertTest extends TestCase } }' ], + 'assertSameOnMemoizedMethodCall' => [ + 'getMessage()); + } + + try { + validateUsername("invalid#1"); + } catch (Exception $e) { + assertSame("b", $e->getMessage()); + } + } + + /** + * @psalm-template ExpectedType + * @psalm-param ExpectedType $expected + * @psalm-param mixed $actual + * @psalm-assert =ExpectedType $actual + */ + function assertSame($expected, $actual): void { + if ($actual !== $expected) { + throw new Exception("Bad"); + } + } + + function validateUsername(string $username): void { + if (strlen($username) < 5) { + throw new Exception("Username must be at least 5 characters long"); + } + }' + ], ]; }