Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\Issues\Issue9388\AnnotationToAttribute;

use PhpParser\Node\Attribute;

final readonly class AttributeDecorator
{
/**
* @param AttributeDecoratorInterface[] $decorators
*/
public function __construct(private array $decorators)
{
}

public function decorate(string $phpAttributeName, Attribute $attribute): void
{
foreach ($this->decorators as $decorator) {
if ($decorator->supports($phpAttributeName)) {
$decorator->decorate($attribute);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\Issues\Issue9388\AnnotationToAttribute;

use PhpParser\Node\Attribute;

interface AttributeDecoratorInterface
{
public function supports(string $phpAttributeName): bool;

public function decorate(Attribute $attribute): void;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\Issues\Issue9388\AnnotationToAttribute;

use PhpParser\Node\Arg;
use PhpParser\Node\ArrayItem;
use PhpParser\Node\Attribute;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\ClassConstFetch;
use PhpParser\Node\Identifier;
use PhpParser\Node\Scalar\String_;
use Rector\Php55\Rector\String_\StringClassNameToClassConstantRector;
use Rector\PhpParser\Node\Value\ValueResolver;

final class ValidateAttributeDecorator implements AttributeDecoratorInterface
{
/**
* @readonly
*/
private ValueResolver $valueResolver;

/**
* @readonly
*/
private StringClassNameToClassConstantRector $stringClassNameToClassConstantRector;

public function __construct(
ValueResolver $valueResolver,
StringClassNameToClassConstantRector $stringClassNameToClassConstantRector
) {
$this->valueResolver = $valueResolver;
$this->stringClassNameToClassConstantRector = $stringClassNameToClassConstantRector;
}

public function supports(string $phpAttributeName): bool
{
return $phpAttributeName === 'TYPO3\CMS\Extbase\Annotation\Validate';
}

public function decorate(Attribute $attribute): void
{
$newArguments = new Array_();

foreach ($attribute->args as $arg) {
$key = $arg->name instanceof Identifier ? new String_($arg->name->toString()) : new String_('validator');

if ($this->valueResolver->isValue($key, 'validator')) {
$classNameString = $this->valueResolver->getValue($arg->value);
if (! is_string($classNameString)) {
continue;
}

$className = ltrim($classNameString, '\\');
$classConstant = $this->stringClassNameToClassConstantRector->refactor(new String_($className));
$value = $classConstant instanceof ClassConstFetch ? $classConstant : $arg->value;
} else {
$value = $arg->value;
}

$newArguments->items[] = new ArrayItem($value, $key);
}

$attribute->args = [new Arg($newArguments)];
}
}
33 changes: 33 additions & 0 deletions tests/Issues/Issue9388/Fixture/fixture.php.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace Rector\Tests\Issues\Issue9388\Fixture;

final class MyClass
{
/**
* @var string
* @TYPO3\CMS\Extbase\Annotation\Validate("NotEmpty")
Copy link
Member

@samsonasik samsonasik Sep 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as I already stated in your other PR, using namespaced annotation inside namespace will become; namespace + annotation. If you need fqcn without \\, add:

use TYPO3;

in use statements or create rule/script init that add \\ prefix early to become;

@\TYPO3\...

Just because in one condition it works, in another condition not works, doesn't mean the original annotation is valid.

Copy link
Contributor Author

@simonschaufi simonschaufi Sep 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just because in one condition it works, in another condition not works, doesn't mean the original annotation is valid.

The question is why is this the case? I know this needs some debugging but there must be something going on why there is a difference. If we find the place, I can provide a fix. It's just very difficult to understand the php doc parsing. Maybe @TomasVotruba has an idea as he originally created the better doc block parser.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is how PHP uses namespaces. Either add use TYPO; or use \\ to FQN the class.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, we only use https://github.com/phpstan/phpdoc-parser here with a bit of wrapping. So the cause might be there.

Copy link
Contributor Author

@simonschaufi simonschaufi Sep 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is how PHP uses namespaces. Either add use TYPO; or use \ to FQN the class.

This was the official TYPO3 way of annotating. I can't just tell everybody to adjust their code. That's why I built a rule to migrate that to a native php attribute. The transformation to a php attribute also works as long as there is no @var string annotation. For some reason this additional annotation is causing problems and I'm trying to figure out why.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That can be behaviour of PHPStan\Analyser\NameScope that unrelated to Rector.

The best way is to add use TYPO3 in your use statements.

For your usecase in case you still want the way it is, you probably needs to implements your own PhpDocNodeDecoratorInterface instance, and decorate resolved_class attribute, special for TYPO3 annotation, then you can replace by its resolved_class value.

interface PhpDocNodeDecoratorInterface
{
public function decorate(PhpDocNode $phpDocNode, Node $phpNode): void;
}

see examples on existing decorator

https://github.com/rectorphp/rector-src/tree/d64f8d876c66cd2def70e603ef1125eb6be2d64c/src/BetterPhpDocParser/PhpDocParser

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you, I'm gonna try this out.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@simonschaufi I got it, it seems needs tweak on IdentifierPhpDocTypeMapper to not replace the existing IdentifierTypeNode on visit, then verify on auto import handling docblock, see PR:

*/
protected $name = '';

/**
* @TYPO3\CMS\Extbase\Annotation\Validate("NotEmpty")
*/
protected $thisWorks = '';
}
-----
<?php

namespace Rector\Tests\Issues\Issue9388\Fixture;

final class MyClass
{
/**
* @var string
*/
#[\TYPO3\CMS\Extbase\Annotation\Validate(['validator' => 'NotEmpty'])]
protected $name = '';

#[\TYPO3\CMS\Extbase\Annotation\Validate(['validator' => 'NotEmpty'])]
protected $thisWorks = '';
}
36 changes: 36 additions & 0 deletions tests/Issues/Issue9388/Issue9388Test.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\Issues\Issue9388;

use Iterator;
use PHPUnit\Framework\Attributes\DataProvider;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
use Rector\ValueObject\PhpVersionFeature;

/**
* @see https://github.com/rectorphp/rector/issues/9388
*/
final class Issue9388Test extends AbstractRectorTestCase
{
#[DataProvider('provideData')]
public function test(string $filePath): void
{
if (PHP_VERSION_ID < PhpVersionFeature::ATTRIBUTES) {
$this->markTestSkipped('Do not execute');
}

$this->doTestFile($filePath);
}

public static function provideData(): Iterator
{
return self::yieldFilesFromDirectory(__DIR__ . '/Fixture');
}

public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configured_rule.php';
}
}
185 changes: 185 additions & 0 deletions tests/Issues/Issue9388/Rule/ExtbaseAnnotationToAttributeRector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\Issues\Issue9388\Rule;

use PhpParser\Node;
use PhpParser\Node\AttributeGroup;
use PhpParser\Node\Stmt\Property;
use PhpParser\Node\Stmt\Use_;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode;
use Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
use Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTagRemover;
use Rector\Comments\NodeDocBlock\DocBlockUpdater;
use Rector\Naming\Naming\UseImportsResolver;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\Php80\NodeAnalyzer\PhpAttributeAnalyzer;
use Rector\Php80\NodeFactory\AttrGroupsFactory;
use Rector\Php80\ValueObject\AnnotationToAttribute;
use Rector\Php80\ValueObject\DoctrineTagAndAnnotationToAttribute;
use Rector\Rector\AbstractRector;
use Rector\Tests\Issues\Issue9388\AnnotationToAttribute\AttributeDecorator;
use Rector\ValueObject\PhpVersionFeature;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

final class ExtbaseAnnotationToAttributeRector extends AbstractRector implements MinPhpVersionInterface
{
/**
* @var AnnotationToAttribute[]
*/
private array $annotationsToAttributes;

public function __construct(
private readonly AttributeDecorator $attributeDecorator,
private readonly AttrGroupsFactory $attrGroupsFactory,
private readonly PhpDocTagRemover $phpDocTagRemover,
private readonly UseImportsResolver $useImportsResolver,
private readonly PhpAttributeAnalyzer $phpAttributeAnalyzer,
private readonly DocBlockUpdater $docBlockUpdater,
private readonly PhpDocInfoFactory $phpDocInfoFactory
) {
$this->annotationsToAttributes = [
new AnnotationToAttribute('TYPO3\CMS\Extbase\Annotation\Validate'),
];
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Change annotation to attribute', [new CodeSample(
<<<'CODE_SAMPLE'
use TYPO3\CMS\Extbase\Annotation as Extbase;

class MyEntity
{
/**
* @Extbase\ORM\Transient()
*/
protected string $myProperty;
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
use TYPO3\CMS\Extbase\Annotation as Extbase;

class MyEntity
{
#[Extbase\ORM\Transient()]
protected string $myProperty;
}
CODE_SAMPLE
)]);
}

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

/**
* @param Property $node
*/
public function refactor(Node $node): ?Node
{
$phpDocInfo = $this->phpDocInfoFactory->createFromNode($node);
if (! $phpDocInfo instanceof PhpDocInfo) {
return null;
}

$uses = $this->useImportsResolver->resolveBareUses();
$annotationAttributeGroups = $this->processDoctrineAnnotationClasses($phpDocInfo, $uses);
if ($annotationAttributeGroups === []) {
return null;
}

$this->docBlockUpdater->updateRefactoredNodeWithPhpDocInfo($node);

foreach ($annotationAttributeGroups as $attributeGroup) {
foreach ($attributeGroup->attrs as $attr) {
$phpAttributeName = $attr->name->getAttribute(AttributeKey::PHP_ATTRIBUTE_NAME);
$this->attributeDecorator->decorate($phpAttributeName, $attr);
}
}

$node->attrGroups = \array_merge($node->attrGroups, $annotationAttributeGroups);
return $node;
}

public function provideMinPhpVersion(): int
{
return PhpVersionFeature::ATTRIBUTES;
}

/**
* @param Use_[] $uses
* @return AttributeGroup[]
*/
private function processDoctrineAnnotationClasses(PhpDocInfo $phpDocInfo, array $uses): array
{
if ($phpDocInfo->getPhpDocNode()->children === []) {
return [];
}

$doctrineTagAndAnnotationToAttributes = [];
$doctrineTagValueNodes = [];
foreach ($phpDocInfo->getPhpDocNode()->children as $phpDocChildNode) {
if (! $phpDocChildNode instanceof PhpDocTagNode) {
continue;
}

if (! $phpDocChildNode->value instanceof DoctrineAnnotationTagValueNode) {
continue;
}

$doctrineTagValueNode = $phpDocChildNode->value;
$annotationToAttribute = $this->matchAnnotationToAttribute($doctrineTagValueNode);
if (! $annotationToAttribute instanceof AnnotationToAttribute) {
continue;
}

// Fix the missing leading slash in most of the wild use cases
if (str_starts_with($doctrineTagValueNode->identifierTypeNode->name, '@TYPO3\CMS')) {
$doctrineTagValueNode->identifierTypeNode->name = str_replace(
'@TYPO3\CMS',
'@\\TYPO3\CMS',
$doctrineTagValueNode->identifierTypeNode->name
);
}

$doctrineTagAndAnnotationToAttributes[] = new DoctrineTagAndAnnotationToAttribute(
$doctrineTagValueNode,
$annotationToAttribute
);
$doctrineTagValueNodes[] = $doctrineTagValueNode;
}

$attributeGroups = $this->attrGroupsFactory->create($doctrineTagAndAnnotationToAttributes, $uses);
if ($this->phpAttributeAnalyzer->hasRemoveArrayState($attributeGroups)) {
return [];
}

foreach ($doctrineTagValueNodes as $doctrineTagValueNode) {
$this->phpDocTagRemover->removeTagValueFromNode($phpDocInfo, $doctrineTagValueNode);
}

return $attributeGroups;
}

private function matchAnnotationToAttribute(
DoctrineAnnotationTagValueNode $doctrineAnnotationTagValueNode
): ?AnnotationToAttribute {
foreach ($this->annotationsToAttributes as $annotationToAttribute) {
if (! $doctrineAnnotationTagValueNode->hasClassName($annotationToAttribute->getTag())) {
continue;
}

return $annotationToAttribute;
}

return null;
}
}
27 changes: 27 additions & 0 deletions tests/Issues/Issue9388/config/configured_rule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Renaming\Rector\Name\RenameClassRector;
use Rector\Tests\Issues\Issue9388\AnnotationToAttribute\AttributeDecorator;
use Rector\Tests\Issues\Issue9388\AnnotationToAttribute\AttributeDecoratorInterface;
use Rector\Tests\Issues\Issue9388\AnnotationToAttribute\ValidateAttributeDecorator;
use Rector\Tests\Issues\Issue9388\Rule\ExtbaseAnnotationToAttributeRector;
use Rector\ValueObject\PhpVersionFeature;

return static function (RectorConfig $rectorConfig): void {
$rectorConfig->autotagInterface(AttributeDecoratorInterface::class);
$rectorConfig->singleton(ValidateAttributeDecorator::class);
$rectorConfig->when(AttributeDecorator::class)->needs('$decorators')->giveTagged(
AttributeDecoratorInterface::class
);

$rectorConfig->importNames(false, false);
$rectorConfig->phpVersion(PhpVersionFeature::ATTRIBUTES);

$rectorConfig->ruleWithConfiguration(RenameClassRector::class, [
'TYPO3\CMS\Extbase\Mvc\Web\Request' => 'TYPO3\CMS\Extbase\Mvc\Request',
]);
$rectorConfig->rule(ExtbaseAnnotationToAttributeRector::class);
};
Loading