Remove chained method or whole expression? #9221
|
Hello! I'd like to remove some method calls in a custom rector rule. This method could be part of a fluent syntax. Let's say, I want to remove
- $var = $object->methodA()->methodB();
+ $var = $object->methodB();
- $var = $object->methodA();
+ $var = $object;
- $object = $object->methodA();
- $object->methodA();Cases 1 & 2 are pretty easy to handle, my rector rule looks like something like this: public function getNodeTypes() : array
{
return [Node\Expr\MethodCall::class, Node\Expr\NullsafeMethodCall::class];
}
/** @param Node\Expr\MethodCall|Node\Expr\NullsafeMethodCall $node */
public function refactor(Node $node) : Node|null
{
foreach ($this->removeMethodCalls as $removeMethodCall) {
if (!$this->isName($node->name, $removeMethodCall->methodName)) {
continue;
}
return $node->var;
}
return null;
}but how to deal with case 3 & 4 ? I think I'd need to remove the whole expression in order to remove the expression, but the approaches are slightly different than when applying the rule on the thanks for your help 🙂 |
Answered by
samsonasik
Jun 16, 2025
Replies: 1 comment 3 replies
|
You can define public function getNodeTypes() : array
{
return [Node\Stmt\Expression::class];
}then, use its if ($node->expr instanceof MethodCall && $this->isName($node->expr->name, $removeMethodCall->methodName)) {
return \PhpParser\NodeVisitor::REMOVE_NODE;
} |
3 replies
Answer selected by
samsonasik
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can define
Expressionstatement for that:then, use its
exprproperty to verify: