From 0825f220fe4bd321d7182656a94bfba4435aa72d Mon Sep 17 00:00:00 2001 From: orklah Date: Sat, 4 Sep 2021 20:22:06 +0200 Subject: [PATCH 1/2] allow ternary to override previous type when reassigning --- .../Statements/Expression/TernaryAnalyzer.php | 12 ++++++++++++ tests/TypeReconciliation/ConditionalTest.php | 11 ++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/Psalm/Internal/Analyzer/Statements/Expression/TernaryAnalyzer.php b/src/Psalm/Internal/Analyzer/Statements/Expression/TernaryAnalyzer.php index ad3adad6c6d..ec95304e074 100644 --- a/src/Psalm/Internal/Analyzer/Statements/Expression/TernaryAnalyzer.php +++ b/src/Psalm/Internal/Analyzer/Statements/Expression/TernaryAnalyzer.php @@ -15,6 +15,7 @@ use Psalm\Type\Reconciler; use function array_filter; +use function array_intersect; use function array_keys; use function array_map; use function array_merge; @@ -232,6 +233,17 @@ function ($c) use ($reconciled_expression_clauses): bool { } } + $redef_var_ifs = array_keys($if_context->getRedefinedVars($context->vars_in_scope)); + $redef_var_else = array_keys($t_else_context->getRedefinedVars($context->vars_in_scope)); + $redef_all = array_intersect($redef_var_ifs, $redef_var_else); + + foreach ($redef_all as $redef_var_id) { + $context->vars_in_scope[$redef_var_id] = Type::combineUnionTypes( + $if_context->vars_in_scope[$redef_var_id], + $t_else_context->vars_in_scope[$redef_var_id] + ); + } + $context->vars_possibly_in_scope = array_merge( $context->vars_possibly_in_scope, $if_context->vars_possibly_in_scope, diff --git a/tests/TypeReconciliation/ConditionalTest.php b/tests/TypeReconciliation/ConditionalTest.php index 5872f54252c..3de456b017e 100644 --- a/tests/TypeReconciliation/ConditionalTest.php +++ b/tests/TypeReconciliation/ConditionalTest.php @@ -2665,7 +2665,16 @@ function ($_valid): void {}; $takesValid($val3); } }' - ] + ], + 'ternaryRedefineAllVars' => [ + ' [ + '$_a===' => "'N'|'Y'", + ] + ], ]; } From e2b594820e98f15922bf832edb33229873efaf54 Mon Sep 17 00:00:00 2001 From: orklah Date: Sat, 4 Sep 2021 20:27:25 +0200 Subject: [PATCH 2/2] fix test --- tests/TypeReconciliation/ConditionalTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/TypeReconciliation/ConditionalTest.php b/tests/TypeReconciliation/ConditionalTest.php index 3de456b017e..5975d5f1493 100644 --- a/tests/TypeReconciliation/ConditionalTest.php +++ b/tests/TypeReconciliation/ConditionalTest.php @@ -2672,7 +2672,7 @@ function ($_valid): void {}; $b = rand(0,1) ? "" : "a"; $b === "a" ? $_a = "Y" : $_a = "N";', 'assertions' => [ - '$_a===' => "'N'|'Y'", + '$_a===' => '"N"|"Y"', ] ], ];