Replace function or method call in wrapped if statement
#7860
-
|
I need a Rector rule which takes a function or method call and wraps it in a conditional When testing, I tried just returning an Are the examples in Rector for replacing expressions and wrapping them in conditional calls? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 2 replies
-
|
Given |
Beta Was this translation helpful? Give feedback.
-
|
Could you show the expected diff, before vs after? |
Beta Was this translation helpful? Give feedback.
-
|
It would be something like the following. But I don't think it is possible with a Rule itself and requires a PostRector. Existing: $password = user_password();Replacement: if (version_compare(\Drupal::VERSION, '9.1.0', '>=')) {
$password = \Drupal::service('password_generator')->generate();
}
else {
$password = user_password();
}The idea is to provide a replacement with backwards compatibility. |
Beta Was this translation helpful? Give feedback.
-
|
You need to replace whole First, define the node types as public function getNodeTypes(): array
{
return [\PhpParser\Node\Stmt\Expression::class];
}Next, verify if the node expr is match with /**
* @param \PhpParser\Node\Stmt\Expression $node
*/
public function refactor(Node $node): ?Node
{
if (! $node->expr instanceof \PhpParser\Node\Expr\Assign) {
return null;
}
if (! $node->expr->expr instanceof \PhpParser\Node\Expr\FuncCall) {
return null;
}
if (! $this->nodeNameResolver->isName($node->expr->expr, 'user_password')) {
return null;
}
// here replace with new If_
$if = \PhpParser\Node\Stmt\If_(
$this->nodeFactory->createFuncCall('version_compare', [
$this->nodeFactory->createClassConstFetch('Drupal', 'VERSION'),
new \PhpParser\Node\Scalar\String_('9.1.0'),
new \PhpParser\Node\Scalar\String_('>='),
])
);
$if->stmts[0] = new \PhpParser\Node\Stmt\Expression(
// here new assign Expr...
);
$if->else = new \PhpParser\Node\Stmt\Else([
new \PhpParser\Node\Stmt\Expression(
$node->expr
]),
);
return $if;
}Above is pseudo code, but you have the idea :) |
Beta Was this translation helpful? Give feedback.
You need to replace whole
Expresssionfor that:First, define the node types as
Expressionstmt:Next, verify if the node expr is match with
Assign