diff --git a/rules-tests/CodingStyle/Rector/Catch_/CatchExceptionNameMatchingTypeRector/Fixture/identical_runs_after_each_other.php.inc b/rules-tests/CodingStyle/Rector/Catch_/CatchExceptionNameMatchingTypeRector/Fixture/identical_runs_after_each_other.php.inc new file mode 100644 index 00000000000..8b9db4ef986 --- /dev/null +++ b/rules-tests/CodingStyle/Rector/Catch_/CatchExceptionNameMatchingTypeRector/Fixture/identical_runs_after_each_other.php.inc @@ -0,0 +1,53 @@ +exception($e); + } + + try { + } catch (Throwable $e) { + $notification = new Notification(); + $notification->exception($e); + } + } +} + +?> +----- +exception($throwable); + } + + try { + } catch (Throwable $throwable) { + $notification = new Notification(); + $notification->exception($throwable); + } + } +} + +?> diff --git a/rules-tests/CodingStyle/Rector/Catch_/CatchExceptionNameMatchingTypeRector/Source/Notification.php b/rules-tests/CodingStyle/Rector/Catch_/CatchExceptionNameMatchingTypeRector/Source/Notification.php new file mode 100644 index 00000000000..32449cf442d --- /dev/null +++ b/rules-tests/CodingStyle/Rector/Catch_/CatchExceptionNameMatchingTypeRector/Source/Notification.php @@ -0,0 +1,7 @@ +var = new Variable($newVariableName); + $this->renameVariableInStmts( $catch, $oldVariableName, @@ -149,6 +150,23 @@ public function refactor(Node $node): ?Node return null; } + private function shouldSkipFollowingCatch(Catch_ $catch, string $newVariableName, string $oldVariableName): bool + { + if ($catch->var instanceof Variable) { + $nextCatchVariableName = $this->getName($catch->var); + + return in_array($nextCatchVariableName, [$newVariableName, $oldVariableName], true); + } + + if (count($catch->types) === 1) { + $soleType = $catch->types[0]->toString(); + + return lcfirst($soleType) === $newVariableName; + } + + return false; + } + private function resolveNewVariableName(string $typeShortName): string { return Strings::replace( @@ -229,12 +247,17 @@ private function replaceNextUsageVariable( $this->traverseNodesWithCallable($nextNode, function (Node $node) use ( $oldVariableName, + $newVariableName, &$nonAssignedVariables ): ?int { if ($node instanceof Assign && $node->var instanceof Variable) { return NodeVisitor::STOP_TRAVERSAL; } + if ($node instanceof Catch_ && $this->shouldSkipFollowingCatch($node, $newVariableName, $oldVariableName)) { + return NodeVisitor::STOP_TRAVERSAL; + } + if (! $node instanceof Variable) { return null; }