|
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 |
|
@@ -101,15 +105,31 @@ public function getNodeTypes(): array |
101 | 105 |
|
102 | 106 | /** |
103 | 107 | * @param Echo_|Expression|Return_ $node |
| 108 | + * @return null|Node|Node[] |
104 | 109 | */ |
105 | | - public function refactor(Node $node): ?Node |
| 110 | + public function refactor(Node $node): null|Node|array |
106 | 111 | { |
107 | 112 | /** @var Match_|null $match */ |
108 | 113 | $match = null; |
109 | 114 | $hasChanged = false; |
110 | 115 |
|
111 | 116 | $scope = ScopeFetcher::fetch($node); |
112 | 117 |
|
| 118 | + if ($node instanceof Expression |
| 119 | + && $node->expr instanceof Assign |
| 120 | + && $node->expr->var instanceof ArrayDimFetch |
| 121 | + && $node->expr->var->var instanceof ArrayDimFetch |
| 122 | + && $node->expr->var->var->dim instanceof Match_) { |
| 123 | + $matchVariable = new Variable($this->variableNaming->createCountedValueName('match', $scope)); |
| 124 | + $expression = new Expression(new Assign($matchVariable, $node->expr->var->var->dim)); |
| 125 | + $expression->setAttribute(AttributeKey::SCOPE, $scope); |
| 126 | + $expression = $this->refactor($expression); |
| 127 | + |
| 128 | + $node->expr->var->var->dim = $matchVariable; |
| 129 | + |
| 130 | + return [$expression, $node]; |
| 131 | + } |
| 132 | + |
113 | 133 | $this->traverseNodesWithCallable( |
114 | 134 | $node, |
115 | 135 | function (Node $subNode) use ($node, &$match, &$hasChanged, $scope) { |
|
0 commit comments