Skip to content

Commit

Permalink
handle return flag for a try/catch/finally (#4746)
Browse files Browse the repository at this point in the history
* handle return flag for a try/catch/finally

* add tests for psalter
  • Loading branch information
orklah committed Dec 1, 2020
1 parent 98053ea commit f0c0ac0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/Psalm/Internal/Analyzer/Statements/Block/TryAnalyzer.php
Expand Up @@ -444,6 +444,7 @@ function ($fq_catch_class) use ($codebase): \Psalm\Type\Atomic\TNamedObject {
$context->loop_scope->final_actions[] = ScopeAnalyzer::ACTION_NONE;
}

$finally_has_returned = false;
if ($stmt->finally) {
if ($try_context->finally_scope) {
$finally_context = clone $context;
Expand All @@ -455,9 +456,7 @@ function ($fq_catch_class) use ($codebase): \Psalm\Type\Atomic\TNamedObject {

$statements_analyzer->analyze($stmt->finally->stmts, $finally_context);

if ($finally_context->has_returned) {
$context->has_returned = true;
}
$finally_has_returned = $finally_context->has_returned;

/** @var string $var_id */
foreach ($finally_context->assigned_var_ids as $var_id => $_) {
Expand Down Expand Up @@ -500,6 +499,9 @@ function ($fq_catch_class) use ($codebase): \Psalm\Type\Atomic\TNamedObject {
}
}

$body_has_returned = !in_array(ScopeAnalyzer::ACTION_NONE, $stmt_control_actions, true);
$context->has_returned = ($body_has_returned && $all_catches_leave) || $finally_has_returned;

return null;
}
}
32 changes: 32 additions & 0 deletions tests/FileManipulation/ReturnTypeManipulationTest.php
Expand Up @@ -607,6 +607,38 @@ function foo(): string {
false,
true,
],
'tryCatchReturn' => [
'<?php
function scope(){
try{
return func();
}
catch(Exception $e){
return null;
}
}
function func(): stdClass{
return new stdClass();
}',
'<?php
function scope(): ?stdClass{
try{
return func();
}
catch(Exception $e){
return null;
}
}
function func(): stdClass{
return new stdClass();
}',
'7.3',
['MissingReturnType'],
false,
true,
],
];
}
}

0 comments on commit f0c0ac0

Please sign in to comment.