rector

Which rule can I use to change variable name?


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?


Solution

  • 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;
        }
    }