Best way to remove node with traverseNodesWithCallable in 0.17.1? #8001
-
QuestionRector 0.17.1 removed effectively removed $this->traverseNodesWithCallable((array) $classMethod->stmts, function (Node $subNode) : ?Node {
if(someConditionThatWeDecide()) {
$this->removeNode($subNode);
}
});What is the best way moving forward for code like this? When changing the |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
|
You can define more You can also traverse with Assuming you're trying to remove a use Rector\Core\Contract\PhpParser\Node\StmtsAwareInterface;
use PhpParser\Node\Stmt;
use PhpParser\NodeTraverser;
use Rector\NodeTypeResolver\Node\AttributeKey;
// ...
$parentStmt = null;
$currentStmtKey = null;
$hasChanged = false;
$this->traverseNodesWithCallable(
(array) $classMethod->stmts,
function (Node $subNode) use ($classMethod, &$parentStmt, &$currentStmtKey, &$hasChanged): ?Node {
// maybe removal will be inside Closure or If, etc
if ($subNode instanceof StmtsAwareInterface) {
$parentStmt = $subNode;
return null;
}
if ($subNode instanceof Stmt) {
$currentStmtKey = $subNode->getAttribute(AttributeKey::STMT_KEY);
return null;
}
// here you remove the Stmt if method call is "foo"
if ($this->isName($methodCall->name, 'foo')) {
// first level, just remove by subnode key
if (! $parentStmt instanceof Node) {
unset($classMethod->stmts[$currentStmtKey]);
} else {
unset($parentStmt->stmts[$currentStmtKey]);
}
$hasChanged = true;
}
return null;
});
if ($hasChanged) {
return $node;
}
return null;I will prepare a blog post for that :) |
Beta Was this translation helpful? Give feedback.
-
|
Thanks for the quick reply! Defining more nodes in |
Beta Was this translation helpful? Give feedback.
-
|
@timmipetit here the blogpost https://getrector.com/blog/rector-017-using-scoped-traverse |
Beta Was this translation helpful? Give feedback.
You can define more
NodeinsidegetNodeTypes()method to point to the correct target node, and usingunset()to specific key of stmt, like what I did in laminas-servicemanager-migration, there isstmt_keyfor that:https://github.com/laminas/laminas-servicemanager-migration/pull/131/files#diff-40da94022f21a80bb7c833406e6092f80e0015c1c7b8f0e2121102affedb86bd
You can also traverse with
StmtsAwareInterface, with "beware", ensure that the stmt is the correct stmt_key by StmtsAwareInterface that wrap it, like what I did in cakephp/upgrade:https://github.com/cakephp/upgrade/pull/236/files#diff-a0b234faceec43fc851a50273b309febcaeda01b537e32eb8f57fd7310496051
Assuming you're trying to remove a
M…