Skip to content

Commit fa0a9a8

Browse files
authored
[TypeDeclaration] Skip try catch finally different type on AddReturnTypeFromTryCatchTypeRector (#7101)
* [TypeDeclaration] Skip try catch finally different type on AddReturnTypeFromTryCatchTypeRector * Fix * add fixture same type
1 parent dc34f6c commit fa0a9a8

3 files changed

Lines changed: 66 additions & 2 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
3+
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddReturnTypeFromTryCatchTypeRector\Fixture;
4+
5+
final class SkipTryCatchFinallyDifferentType
6+
{
7+
public function run()
8+
{
9+
try {
10+
return 1;
11+
} catch (\RuntimeException $e) {
12+
return 2;
13+
} finally {
14+
return "A";
15+
}
16+
}
17+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddReturnTypeFromTryCatchTypeRector\Fixture;
4+
5+
final class TryCatchFinallySameType
6+
{
7+
public function run()
8+
{
9+
try {
10+
return 1;
11+
} catch (\RuntimeException $e) {
12+
return 2;
13+
} finally {
14+
return 3;
15+
}
16+
}
17+
}
18+
19+
?>
20+
-----
21+
<?php
22+
23+
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddReturnTypeFromTryCatchTypeRector\Fixture;
24+
25+
final class TryCatchFinallySameType
26+
{
27+
public function run(): int
28+
{
29+
try {
30+
return 1;
31+
} catch (\RuntimeException $e) {
32+
return 2;
33+
} finally {
34+
return 3;
35+
}
36+
}
37+
}
38+
39+
?>

rules/TypeDeclaration/Rector/ClassMethod/AddReturnTypeFromTryCatchTypeRector.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use PhpParser\Node\Expr;
99
use PhpParser\Node\Stmt\Catch_;
1010
use PhpParser\Node\Stmt\ClassMethod;
11+
use PhpParser\Node\Stmt\Finally_;
1112
use PhpParser\Node\Stmt\Return_;
1213
use PhpParser\Node\Stmt\TryCatch;
1314
use PHPStan\Type\Type;
@@ -128,6 +129,13 @@ public function refactor(Node $node): ?Node
128129

129130
$catchReturnTypes[] = $currentCatchType;
130131
}
132+
133+
if ($tryCatch->finally instanceof Finally_) {
134+
$finallyReturnType = $this->matchReturnType($tryCatch->finally);
135+
if ($finallyReturnType instanceof Type) {
136+
$catchReturnTypes[] = $finallyReturnType;
137+
}
138+
}
131139
}
132140

133141
if (! $tryReturnType instanceof Type) {
@@ -149,9 +157,9 @@ public function refactor(Node $node): ?Node
149157
return $node;
150158
}
151159

152-
private function matchReturnType(TryCatch|Catch_ $tryOrCatch): ?Type
160+
private function matchReturnType(TryCatch|Catch_|Finally_ $tryOrCatchOrFinally): ?Type
153161
{
154-
foreach ($tryOrCatch->stmts as $stmt) {
162+
foreach ($tryOrCatchOrFinally->stmts as $stmt) {
155163
if (! $stmt instanceof Return_) {
156164
continue;
157165
}

0 commit comments

Comments
 (0)