Trying to replace expression (Expr_FuncCall) with statement (Stmt_Echo) #8172
-
I'm trying to write my first own rector class but I'm having trouble. I want to replace a function call with a echo statement. My previous function took two arguments, the replacement should only use the first. Below is what I tried. According to the error message mentioned in the title, I can not replace an expression with a statement. How do I convert the statement into an expression? class PtlnRector extends AbstractRector
{
/** @inheritdoc */
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Replace ptln() calls with echo', [
new CodeSample(
<<<'CODE_SAMPLE'
ptln('Hello World', 7);
CODE_SAMPLE,
<<<'CODE_SAMPLE'
echo 'Hello World';
CODE_SAMPLE
),
]);
}
/** @inheritdoc */
public function getNodeTypes(): array
{
return [FuncCall::class];
}
/** @inheritdoc */
public function refactor(Node $node)
{
if (!$this->isName($node, 'ptln')) return null;
return new Echo_([
$node->args[0]->value
]);
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
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\FuncCall) {
return null;
}
if (! $this->nodeNameResolver->isName($node->expr, 'ptln')) {
return null;
}
// here replace with Echo_
return new Echo_([
$node->expr->args[0]->value
]);
} Above is pseudo code, but you have the idea :) |
Beta Was this translation helpful? Give feedback.
You need to replace whole
Expresssion
for that:First, define the node types as
Expression
stmt:Next, verify if the node expr is match with
FuncCall