Skip to content

Commit

Permalink
[CodeQuality] Handle crash previous duplicated on ThrowWithPreviousEx…
Browse files Browse the repository at this point in the history
…ceptionRector (#6773)

* [CodeQuality] Handle crash previous duplicated on ThrowWithPreviousExceptionRector

* Fix

* fix phpstan

* [ci-review] Rector Rectify

---------

Co-authored-by: GitHub Action <actions@github.com>
  • Loading branch information
samsonasik and actions-user authored Mar 7, 2025
1 parent 01e60df commit 483849a
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\Catch_\ThrowWithPreviousExceptionRector\Fixture;

class NamedArgumentPrevious
{
public function run()
{
try {
throw new \Exception('foo');
} catch (\Throwable $e) {
throw new \RuntimeException(previous: $e);
}
}
}

?>
-----
<?php

namespace Rector\Tests\CodeQuality\Rector\Catch_\ThrowWithPreviousExceptionRector\Fixture;

class NamedArgumentPrevious
{
public function run()
{
try {
throw new \Exception('foo');
} catch (\Throwable $e) {
throw new \RuntimeException(message: $e->getMessage(), code: $e->getCode(), previous: $e);
}
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -140,16 +140,19 @@ private function refactorThrow(Throw_ $throw, Variable $catchedThrowableVariable
return null;
}

if (! isset($new->getArgs()[0])) {
/** @var Arg|null $messageArgument */
$messageArgument = $new->args[0] ?? null;
$shouldUseNamedArguments = $messageArgument instanceof Arg && $messageArgument->name instanceof Identifier;

if (! isset($new->args[0])) {
// get previous message
$getMessageMethodCall = new MethodCall($catchedThrowableVariable, 'getMessage');
$new->args[0] = new Arg($getMessageMethodCall);
} elseif ($new->args[0] instanceof Arg && $new->args[0]->name instanceof Identifier && $new->args[0]->name->toString() === 'previous' && $this->nodeComparator->areNodesEqual($new->args[0]->value, $catchedThrowableVariable)) {
$new->args[0]->name->name = 'message';
$new->args[0]->value = new MethodCall($catchedThrowableVariable, 'getMessage');
}

/** @var Arg $messageArgument */
$messageArgument = $new->getArgs()[0];
$shouldUseNamedArguments = $messageArgument->name !== null;

if (! isset($new->getArgs()[1])) {
// get previous code
$new->args[1] = new Arg(
Expand Down

0 comments on commit 483849a

Please sign in to comment.