trying to delete a line with a custom rector rule #9085
-
Here's my Rector rule / rector.php (to make for an easier demo I've just put the Rector rule in rector.php): <?php
use Rector\Config\RectorConfig;
use PhpParser\Node;
use PhpParser\Node\Expr\New_;
use PhpParser\NodeTraverser;
use PHPStan\Type\ObjectType;
use Rector\Contract\Rector\RectorInterface;
use Rector\Rector\AbstractRector;
class TestRector extends AbstractRector implements RectorInterface
{
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes() : array
{
return [New_::class];
}
/**
* @param New_ $node
*/
public function refactor(Node $node) : ?int
{
if ($this->isObjectType($node->class, new ObjectType('A'))) {
return NodeTraverser::REMOVE_NODE;
}
return null;
}
}
return RectorConfig::configure()
->withRules([
TestRector::class,
]); I'm doing I have one file in src/ - src/test.php: <?php
class A {}
$a = new A();
echo 'all done!'; When I run my Rector rule I get this: c:\games\rector2\ c:\phptst\rector
The fact that the debug text is being cut off is most unhelpful. I I shrink the Windows 11 PowerShell window down as much as I can and then rerun Rector I get this:
So I guess the RemoveDeadReturnRector does And, for what it's worth, I'm aware that this Rector rule, by itself, would result in a src/test.php that doesn't run, but that doesn't change the fact that https://getrector.com/blog/5-tricks-to-write-better-custom-rules#content-4-return-nodetraverserremovenode-to-remove-the-stmt-node implies that the rector rule should remove that line when, in fact, it doesn't. Any ideas? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You need to remove Expression statement for that, for example https://getrector.com/custom-rule/9698dbb3-b6a8-442e-ac1f-bb9920272d0c |
Beta Was this translation helpful? Give feedback.
You need to remove Expression statement for that, for example
https://getrector.com/custom-rule/9698dbb3-b6a8-442e-ac1f-bb9920272d0c