|
8 | 8 | use PhpParser\Node\Arg; |
9 | 9 | use PhpParser\Node\ArrayItem; |
10 | 10 | use PhpParser\Node\Expr; |
| 11 | +use PhpParser\Node\Expr\ArrayDimFetch; |
11 | 12 | use PhpParser\Node\Expr\ArrowFunction; |
12 | 13 | use PhpParser\Node\Expr\Assign; |
13 | 14 | use PhpParser\Node\Expr\BinaryOp; |
|
19 | 20 | use PhpParser\Node\Expr\NullsafeMethodCall; |
20 | 21 | use PhpParser\Node\Expr\StaticCall; |
21 | 22 | use PhpParser\Node\Expr\Throw_; |
| 23 | +use PhpParser\Node\Expr\Variable; |
22 | 24 | use PhpParser\Node\MatchArm; |
23 | 25 | use PhpParser\Node\Stmt; |
24 | 26 | use PhpParser\Node\Stmt\Break_; |
|
29 | 31 | use PhpParser\Node\Stmt\Switch_; |
30 | 32 | use PhpParser\NodeVisitor; |
31 | 33 | use PHPStan\Analyser\Scope; |
| 34 | +use Rector\Naming\Naming\VariableNaming; |
32 | 35 | use Rector\NodeTypeResolver\Node\AttributeKey; |
33 | 36 | use Rector\Php72\NodeFactory\AnonymousFunctionFactory; |
34 | 37 | use Rector\PHPStan\ScopeFetcher; |
|
44 | 47 | final class DowngradeMatchToSwitchRector extends AbstractRector |
45 | 48 | { |
46 | 49 | public function __construct( |
47 | | - private readonly AnonymousFunctionFactory $anonymousFunctionFactory |
| 50 | + private readonly AnonymousFunctionFactory $anonymousFunctionFactory, |
| 51 | + private readonly VariableNaming $variableNaming |
48 | 52 | ) { |
49 | 53 | } |
50 | 54 |
|
@@ -102,14 +106,37 @@ public function getNodeTypes(): array |
102 | 106 | /** |
103 | 107 | * @param Echo_|Expression|Return_ $node |
104 | 108 | */ |
105 | | - public function refactor(Node $node): ?Node |
| 109 | + public function refactor(Node $node): null|Node|array |
106 | 110 | { |
107 | 111 | /** @var Match_|null $match */ |
108 | 112 | $match = null; |
109 | 113 | $hasChanged = false; |
110 | 114 |
|
111 | 115 | $scope = ScopeFetcher::fetch($node); |
112 | 116 |
|
| 117 | + if ($node instanceof Expression |
| 118 | + && $node->expr instanceof Assign |
| 119 | + && $node->expr->var instanceof ArrayDimFetch |
| 120 | + && $node->expr->var->var instanceof ArrayDimFetch |
| 121 | + && $node->expr->var->var->dim instanceof Match_) { |
| 122 | + $matchVariable = new Variable($this->variableNaming->createCountedValueName('match', $scope)); |
| 123 | + $expression = new Expression(new Assign($matchVariable, $node->expr->var->var->dim)); |
| 124 | + $expression->setAttribute(AttributeKey::SCOPE, $scope); |
| 125 | + $refactored = $this->refactor($expression); |
| 126 | + |
| 127 | + if ($refactored === null) { |
| 128 | + return null; |
| 129 | + } |
| 130 | + |
| 131 | + $node->expr->var->var->dim = $matchVariable; |
| 132 | + |
| 133 | + $stmts = is_array($refactored) |
| 134 | + ? $refactored : |
| 135 | + [$refactored]; |
| 136 | + |
| 137 | + return [...$stmts, $node]; |
| 138 | + } |
| 139 | + |
113 | 140 | $this->traverseNodesWithCallable( |
114 | 141 | $node, |
115 | 142 | function (Node $subNode) use ($node, &$match, &$hasChanged, $scope) { |
|
0 commit comments