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 5f584bc5593..25312d18b91 100644 --- a/tests/TypeReconciliation/ConditionalTest.php +++ b/tests/TypeReconciliation/ConditionalTest.php @@ -2665,7 +2665,16 @@ function ($_valid): void {}; $takesValid($val3); } }' - ] + ], + 'ternaryRedefineAllVars' => [ + ' [ + '$_a===' => '"N"|"Y"', + ] + ], ]; }