Skip to content

[symfony] [GetFunctionsToAsTwigFunctionAttributeRector] Extends should be removedΒ #9361

@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.

https://github.com/rectorphp/rector-symfony/blob/c1dcdae150a5f2f687f32544097117c420a56819/rules/Symfony73/Rector/Class_/GetFunctionsToAsTwigFunctionAttributeRector.php#L57

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

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