Rector PHP: Unable to add array index to rector rule

284 views Asked by At

Using Rector, I'm trying to convert the following.

$integer = some_made_up_function_call($parm1, $parm2);

Into this:

$integer = $parm1->made_up_method_call($parm2)['hard_coded_index'];

My issue is with the ['hard_coded_index'] at the end. I can’t figure out how to accomplish that. What I have so far is.

public function refactor(Node $node): ?Node
{
    if (! $this->isName($node->name, 'some_made_up_function_call')) {
        return null;
    }

    $firstParameter = new Node\Expr\Variable($node->args[0]->value->name);

    return new Node\Expr\MethodCall(
        $firstParameter, 
        'made_up_method_call', 
        [$node->args[1]]
    );
}
1

There are 1 answers

0
Guido Faecke On

All right, I figured it out...

public function refactor(Node $node): ?Node
{
    if (! $this->isName($node->name, 'some_made_up_function_call')) {
        return null;
    }

    $conn = new Node\Expr\Variable($node->args[0]->value->name);

    $methodCall = new Node\Expr\MethodCall($conn, 'made_up_method_call', [$node->args[1]]);
    $arrayKey   = new Node\Scalar\String_('hard_coded_index');

    return new Node\Expr\ArrayDimFetch($methodCall, $arrayKey);
}