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)];
}
}
25 changes: 25 additions & 0 deletions tests/Issues/Issue9388/Fixture/fixture.php.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace Rector\Tests\Issues\Issue9388\Fixture;

final class MyClass
{
/**
* @var string
* @TYPO3\CMS\Extbase\Annotation\Validate("NotEmpty")
*/
protected $name = '';
}
-----
<?php

namespace Rector\Tests\Issues\Issue9388\Fixture;

final class MyClass
{
/**
* @var string
*/
#[\TYPO3\CMS\Extbase\Annotation\Validate(['validator' => 'NotEmpty'])]
protected $name = '';
}
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
);
}
Comment on lines +145 to +151
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 why when you flip the rule, the rule is "working", while actually invalid, as the original namespaced name is current namespace + value identifier if no \\ prefix, so you're changing behaviour of valid identifier.

Add use TYPO, and you will have correct detection :)


$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