Skip to content

[GetFunctionsToAsTwigFunctionAttributeRector] Extends should be removedΒ #822

@cvergne

Description

@cvergne

Hello,

While using Rector to upgrade a Symfony project, it applied the GetFunctionsToAsTwigFunctionAttributeRector rule but then after the change, Symfony throws the error :

The class "{{classname}}" cannot extend "Twig\Extension\AbstractExtension" and use the "#[Twig\Attribute\AsTwigFunction]" attribute on method "{{method}}()", choose one or the other.

As seen in the link given into the code, the extends AbstractExtension is removed in the example with the attribute.

So the RectorRule should also remove the extends AbstractExtension from the class.
Also, the file should be skipped if all defined functions in getFunctions does not call a function inside the current class (i.e: a static method from another class), because it breaks the class as we need the extends for getFunctions but we should not have it for a "moved to attribute" function.

I never have contributed before to Rector so I don't know when I'll have time to try to fix it, but if someone knows how to fix it, don't hesitate to do it :)

The fixed sample should be

                new CodeSample(
                    <<<'CODE_SAMPLE'
use Twig\Extension\AbstractExtension;

class SomeClass extends AbstractExtension
{
    public function getFunctions()
    {
        return [
            new \Twig\TwigFunction('function_name', [$this, 'localMethod']),
        ];
    }

    public function localMethod($value)
    {
        return $value;
    }
}
CODE_SAMPLE
                    ,
                    <<<'CODE_SAMPLE'
use Twig\Extension\AbstractExtension;
use Twig\Attribute\AsTwigFunction;

class SomeClass
{
    #[AsTwigFunction('function_name')]
    public function localMethod($value)
    {
        return $value;
    }
}
CODE_SAMPLE

but if we have :

    public function getFunctions()
    {
        return [
			new \Twig\TwigFunction('static_function_name', [OtherClass, 'myStaticMethod']),
            new \Twig\TwigFunction('function_name', [$this, 'localMethod']),
        ];
    }

the whole file should be skipped :)

Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions