Which rule can I use to change variable name?

469 Views Asked by At

I need to replace all occurencies of $connection with $link?

I know I could do with a regexp replacement using my IDE, but I need to be able to re-run the sostitution automatically.

So I want to use rector.

Is there a way to replace a var name ? Which is the rule name?

2

There are 2 best solutions below

0
On BEST ANSWER

I create a custom rule, very specific for my needs

<?php

namespace Rules;


use PhpParser\Node;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use PhpParser\Node\Expr\Variable;
class ReplaceConnectionVarNameWithLink extends AbstractRector
{

    public function getNodeTypes(): array
    {
        return [
          Variable::class
        ];
    }

    public function getRuleDefinition(): \Symplify\RuleDocGenerator\ValueObject\RuleDefinition
    {
        return new RuleDefinition(
            'rename $connect into $link',
            []
        );
    }

    public function refactor(\PhpParser\Node $node)
    {

        if (!$this->isName( $node, 'connection')) {
            // return null to skip it
            return null;
        }

        $node->name = "link";
        return $node;
    }
}
0
On

There are a couple of potentially suitable rules & sets:

There is also the '\Rector\Set\ValueObject\SetList::NAMING' set that can be enabled in rector.php that will perform some similar rules, like renaming variables according to the type.

The complete set of basic rules (not including framework or library-specific) are at https://github.com/rectorphp/rector/blob/main/docs/rector_rules_overview.md