Skip to content

Commit

Permalink
Refactor DowngradePipeToMultiCatchExceptionRector to work directly wi…
Browse files Browse the repository at this point in the history
…th stmts (#2245)
  • Loading branch information
TomasVotruba committed May 6, 2022
1 parent 176d6d7 commit 6d814fb
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,6 @@ function pipedExceptionCatch()
// ...
}

try {
// Some code...
} catch (ExceptionType1|ExceptionType2 $e) {
// Code to handle the exception
}

try {
// Some code...
} catch (ExceptionType1 $e) {
Expand Down Expand Up @@ -56,14 +50,6 @@ function pipedExceptionCatch()
} catch (ExceptionType2 $e) {
// Code to handle the exception
}

try {
// Some code...
} catch (ExceptionType1 $e) {
// Code to handle the exception
} catch (ExceptionType2 $e) {
// Code to handle the exception
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Rector\Tests\DowngradePhp71\Rector\TryCatch\DowngradePipeToMultiCatchExceptionRector\Fixture;

function singleTryCatch()
{
try {
// Some code...
} catch (ExceptionType1|ExceptionType2 $e) {
// Code to handle the exception
}
}

?>
-----
<?php

namespace Rector\Tests\DowngradePhp71\Rector\TryCatch\DowngradePipeToMultiCatchExceptionRector\Fixture;

function singleTryCatch()
{
try {
// Some code...
} catch (ExceptionType1 $e) {
// Code to handle the exception
} catch (ExceptionType2 $e) {
// Code to handle the exception
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -57,27 +57,29 @@ public function getNodeTypes(): array
*/
public function refactor(Node $node): ?Node
{
$originalCatches = $node->catches;
$hasChanged = false;

foreach ($node->catches as $key => $catch) {
if (count($catch->types) === 1) {
continue;
}

$types = $catch->types;
$node->catches[$key]->types = [$catch->types[0]];
foreach ($types as $keyCatchType => $catchType) {
if ($keyCatchType === 0) {
continue;
}
$catchTypes = $catch->types;

/** @var Node\Name $firstType */
$firstType = array_shift($catchTypes);

$catch->types = [$firstType];

foreach ($catchTypes as $catchType) {
$newCatch = new Catch_([$catchType], $catch->var, $catch->stmts);
array_splice($node->catches, $key + 1, 0, [$newCatch]);

$this->nodesToAddCollector->addNodeAfterNode(
new Catch_([$catchType], $catch->var, $catch->stmts),
$node->catches[$key]
);
$hasChanged = true;
}
}

if ($this->nodeComparator->areNodesEqual($originalCatches, $node->catches)) {
if (! $hasChanged) {
return null;
}

Expand Down

0 comments on commit 6d814fb

Please sign in to comment.