1212use PhpParser \Node \Stmt \Expression ;
1313use PhpParser \Node \Stmt \Nop ;
1414use PhpParser \Node \Stmt \TryCatch ;
15+ use PHPStan \Reflection \ReflectionProvider ;
1516use PHPStan \Type \ObjectType ;
1617use Rector \Rector \AbstractRector ;
1718use Symplify \RuleDocGenerator \ValueObject \CodeSample \CodeSample ;
2223 */
2324final class RemoveDeadCatchRector extends AbstractRector
2425{
26+ public function __construct (
27+ private readonly ReflectionProvider $ reflectionProvider
28+ ) {
29+ }
30+
2531 public function getRuleDefinition (): RuleDefinition
2632 {
2733 return new RuleDefinition ('Remove dead catches ' , [new CodeSample (
@@ -154,7 +160,17 @@ private function shouldSkipNextCatchClassParentWithSpecialTreatment(
154160 return true ;
155161 }
156162
157- if (! $ this ->isObjectType ($ fullyQualified , new ObjectType ($ nextCatchType ->toString ()))) {
163+ // Throwable/Exception catch anything, so the current catch is never dead against them,
164+ // even when the current type cannot be resolved to prove the parent relation
165+ $ catchesAnything = in_array (
166+ ltrim ($ nextCatchType ->toString (), '\\' ),
167+ ['Throwable ' , 'Exception ' ],
168+ true
169+ );
170+
171+ // only skip when the next catch is provably unrelated; an unresolvable next type
172+ // might be a parent of the current one, so removing the catch would change behavior
173+ if (! $ catchesAnything && $ this ->isProvablyUnrelated ($ fullyQualified , $ nextCatchType )) {
158174 continue ;
159175 }
160176
@@ -166,6 +182,19 @@ private function shouldSkipNextCatchClassParentWithSpecialTreatment(
166182 return false ;
167183 }
168184
185+ private function isProvablyUnrelated (FullyQualified $ current , FullyQualified $ next ): bool
186+ {
187+ if (! $ this ->reflectionProvider ->hasClass ($ current ->toString ())) {
188+ return false ;
189+ }
190+
191+ if (! $ this ->reflectionProvider ->hasClass ($ next ->toString ())) {
192+ return false ;
193+ }
194+
195+ return ! $ this ->isObjectType ($ current , new ObjectType ($ next ->toString ()));
196+ }
197+
169198 /**
170199 * @param Stmt[] $stmts
171200 */
0 commit comments