diff --git a/rules-tests/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector/WithoutInheritedCode/Fixture/add_previous_named_argument.php.inc b/rules-tests/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector/WithoutInheritedCode/Fixture/add_previous_named_argument.php.inc new file mode 100644 index 00000000000..5e786e9767c --- /dev/null +++ b/rules-tests/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector/WithoutInheritedCode/Fixture/add_previous_named_argument.php.inc @@ -0,0 +1,41 @@ +doSomething(); + } catch (Throwable $throwable) { + throw new RuntimeException('Failed'); + } + } +} + +?> +----- +doSomething(); + } catch (Throwable $throwable) { + throw new RuntimeException('Failed', previous: $throwable); + } + } +} + +?> diff --git a/rules-tests/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector/WithoutInheritedCode/Fixture/remove_inherited_get_code.php.inc b/rules-tests/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector/WithoutInheritedCode/Fixture/remove_inherited_get_code.php.inc new file mode 100644 index 00000000000..52495c61072 --- /dev/null +++ b/rules-tests/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector/WithoutInheritedCode/Fixture/remove_inherited_get_code.php.inc @@ -0,0 +1,77 @@ +doSomething(); + } catch (Throwable $e) { + throw new RuntimeException('Failed', $e->getCode(), $e); + } + } + + public function positionalCodeOnly(): void + { + try { + $this->doSomething(); + } catch (Throwable $e) { + throw new RuntimeException('Failed', $e->getCode()); + } + } + + public function namedArguments(): void + { + try { + $this->doSomething(); + } catch (Throwable $e) { + throw new RuntimeException('Failed', code: $e->getCode(), previous: $e); + } + } +} + +?> +----- +doSomething(); + } catch (Throwable $e) { + throw new RuntimeException('Failed', previous: $e); + } + } + + public function positionalCodeOnly(): void + { + try { + $this->doSomething(); + } catch (Throwable $e) { + throw new RuntimeException('Failed', previous: $e); + } + } + + public function namedArguments(): void + { + try { + $this->doSomething(); + } catch (Throwable $e) { + throw new RuntimeException('Failed', previous: $e); + } + } +} + +?> diff --git a/rules-tests/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector/WithoutInheritedCode/Fixture/skip_explicit_code_and_existing_previous.php.inc b/rules-tests/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector/WithoutInheritedCode/Fixture/skip_explicit_code_and_existing_previous.php.inc new file mode 100644 index 00000000000..90d06c0f2a3 --- /dev/null +++ b/rules-tests/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector/WithoutInheritedCode/Fixture/skip_explicit_code_and_existing_previous.php.inc @@ -0,0 +1,36 @@ +doSomething(); + } catch (Throwable $e) { + throw new RuntimeException('Not found', 404, $e); + } + } + + public function skipNonCapturingCatch(): void + { + try { + $this->doSomething(); + } catch (Throwable) { + throw new RuntimeException('Failed'); + } + } + + public function skipAlreadyNamedPrevious(): void + { + try { + $this->doSomething(); + } catch (Throwable $e) { + throw new RuntimeException('Failed', previous: $e); + } + } +} diff --git a/rules-tests/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector/WithoutInheritedCode/WithoutInheritedCodeTest.php b/rules-tests/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector/WithoutInheritedCode/WithoutInheritedCodeTest.php new file mode 100644 index 00000000000..9cafd9a2e6d --- /dev/null +++ b/rules-tests/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector/WithoutInheritedCode/WithoutInheritedCodeTest.php @@ -0,0 +1,28 @@ +doTestFile($filePath); + } + + public static function provideData(): Iterator + { + return self::yieldFilesFromDirectory(__DIR__ . '/Fixture'); + } + + public function provideConfigFilePath(): string + { + return __DIR__ . '/config/configured_rule.php'; + } +} diff --git a/rules-tests/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector/WithoutInheritedCode/config/configured_rule.php b/rules-tests/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector/WithoutInheritedCode/config/configured_rule.php new file mode 100644 index 00000000000..1961f904cd0 --- /dev/null +++ b/rules-tests/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector/WithoutInheritedCode/config/configured_rule.php @@ -0,0 +1,11 @@ +withConfiguredRule(ThrowWithPreviousExceptionRector::class, [ + ThrowWithPreviousExceptionRector::INHERIT_CODE => false, + ]); diff --git a/rules/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector.php b/rules/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector.php index 73b177e3038..91989a814ad 100644 --- a/rules/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector.php +++ b/rules/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector.php @@ -6,6 +6,7 @@ use PhpParser\Node; use PhpParser\Node\Arg; +use PhpParser\Node\Expr; use PhpParser\Node\Expr\MethodCall; use PhpParser\Node\Expr\New_; use PhpParser\Node\Expr\Throw_; @@ -19,18 +20,28 @@ use PHPStan\Reflection\ReflectionProvider; use PHPStan\Type\ObjectType; use PHPStan\Type\TypeCombinator; +use Rector\Contract\Rector\ConfigurableRectorInterface; use Rector\NodeTypeResolver\Node\AttributeKey; use Rector\Rector\AbstractRector; use Rector\RuleDoc\CodeSample\CodeSample; +use Rector\RuleDoc\CodeSample\ConfiguredCodeSample; use Rector\RuleDoc\RuleDefinition; use Rector\StaticTypeMapper\Resolver\ClassNameFromObjectTypeResolver; use Rector\ValueObject\MethodName; +use Webmozart\Assert\Assert; /** * @see \Rector\Tests\CodeQuality\Rector\Catch_\ThrowWithPreviousExceptionRector\ThrowWithPreviousExceptionRectorTest */ -final class ThrowWithPreviousExceptionRector extends AbstractRector +final class ThrowWithPreviousExceptionRector extends AbstractRector implements ConfigurableRectorInterface { + /** + * @api + */ + public const string INHERIT_CODE = 'inherit_code'; + + private bool $inheritCode = true; + private const int DEFAULT_EXCEPTION_ARGUMENT_POSITION = 2; public function __construct( @@ -45,37 +56,69 @@ public function getRuleDefinition(): RuleDefinition [ new CodeSample( <<<'CODE_SAMPLE' -class SomeClass -{ - public function run() - { - try { - $someCode = 1; - } catch (Throwable $throwable) { - throw new \RuntimeException('ups'); - } - } -} -CODE_SAMPLE + class SomeClass + { + public function run() + { + try { + $someCode = 1; + } catch (Throwable $throwable) { + throw new \RuntimeException('ups'); + } + } + } + CODE_SAMPLE , <<<'CODE_SAMPLE' -class SomeClass -{ - public function run() - { - try { - $someCode = 1; - } catch (Throwable $throwable) { - throw new \RuntimeException('ups', $throwable->getCode(), $throwable); - } - } -} -CODE_SAMPLE + class SomeClass + { + public function run() + { + try { + $someCode = 1; + } catch (Throwable $throwable) { + throw new \RuntimeException('ups', $throwable->getCode(), $throwable); + } + } + } + CODE_SAMPLE + ), + new ConfiguredCodeSample( + <<<'CODE_SAMPLE' + try { + $someCode = 1; + } catch (Throwable $throwable) { + throw new \RuntimeException('ups', $throwable->getCode()); + } + CODE_SAMPLE + , + <<<'CODE_SAMPLE' + try { + $someCode = 1; + } catch (Throwable $throwable) { + throw new \RuntimeException('ups', previous: $throwable); + } + CODE_SAMPLE + , + [ + self::INHERIT_CODE => false, + ] ), ] ); } + /** + * @param array $configuration + */ + public function configure(array $configuration): void + { + $inheritCode = $configuration[self::INHERIT_CODE] ?? true; + Assert::boolean($inheritCode); + + $this->inheritCode = $inheritCode; + } + /** * @return array> */ @@ -134,6 +177,10 @@ private function refactorThrow(Throw_ $throw, Variable $caughtThrowableVariable) return null; } + if (! $this->inheritCode) { + return $this->refactorThrowWithoutCode($new, $caughtThrowableVariable); + } + $exceptionArgumentPosition = $this->resolveExceptionArgumentPosition($new->class); if ($exceptionArgumentPosition === null) { return null; @@ -212,6 +259,75 @@ private function refactorThrow(Throw_ $throw, Variable $caughtThrowableVariable) return NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN; } + /** + * Pass the previous exception as named "previous" argument and drop "$caught->getCode()", as the parent constructor inherits it + */ + private function refactorThrowWithoutCode(New_ $new, Variable $caughtThrowableVariable): ?int + { + $hasChanged = false; + + foreach ($new->getArgs() as $position => $arg) { + $isCodeArgument = $arg->name instanceof Identifier + ? $arg->name->toString() === 'code' + : $position === 1; + + if (! $isCodeArgument || ! $this->isCaughtThrowableGetCode($arg->value, $caughtThrowableVariable)) { + continue; + } + + unset($new->args[$position]); + $new->args = array_values($new->args); + $hasChanged = true; + + foreach ($new->getArgs() as $remainingArg) { + if (! $remainingArg->name instanceof Identifier && $this->nodeComparator->areNodesEqual( + $remainingArg->value, + $caughtThrowableVariable + )) { + $remainingArg->name = new Identifier('previous'); + } + } + + break; + } + + if (! $this->hasArgument($new, 'previous') + && $new->getArg('previous', 2) === null + && ! $this->hasPositionalCaughtThrowable($new, $caughtThrowableVariable) + && $this->hasParameter($new, 'previous') + ) { + $new->args[] = new Arg($caughtThrowableVariable, name: new Identifier('previous')); + $hasChanged = true; + } + + if (! $hasChanged) { + return null; + } + + // fix broken format preserving printers, see https://github.com/rectorphp/rector/issues/5576 + $new->setAttribute(AttributeKey::ORIGINAL_NODE, null); + + return NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN; + } + + private function isCaughtThrowableGetCode(Expr $expr, Variable $caughtThrowableVariable): bool + { + return $expr instanceof MethodCall + && $this->isName($expr->name, 'getCode') + && $this->nodeComparator->areNodesEqual($expr->var, $caughtThrowableVariable); + } + + private function hasPositionalCaughtThrowable(New_ $new, Variable $caughtThrowableVariable): bool + { + return array_any( + $new->getArgs(), + fn (Arg $arg): bool => ! $arg->name instanceof Identifier && $this->nodeComparator->areNodesEqual( + $arg->value, + $caughtThrowableVariable + ) + ); + } + private function hasParameter(New_ $new, string $parameterName): bool { $className = $this->getName($new->class);