Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Rule to convert action to attributes #257

Merged
merged 27 commits into from
Mar 8, 2024
Merged
Show file tree
Hide file tree
Changes from 25 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
1b8c349
WIP: Rule to convert action to attributes
andypost Oct 29, 2023
4ec1177
Rebase on main and move rector to Drupal10 namespace
bbrala Dec 10, 2023
ecf029a
Add basic unit test for ActionAnnotationToAttributeRector.
bbrala Dec 10, 2023
407fb52
Fix codestyle
bbrala Dec 10, 2023
d936f39
Fix namespace in config for ActionAnnotationToAttributeRector
bbrala Dec 10, 2023
bbe8c03
The label should be "action_label",
bbrala Dec 10, 2023
b383c04
Fix phpstan
bbrala Dec 10, 2023
c0fbf2e
Add test for other possible translation attribute arguments
bbrala Dec 10, 2023
47c1bcc
Add test for situation where the attribute already exists
bbrala Dec 10, 2023
0947c65
If action attribute is already present, do not add it again.
bbrala Dec 10, 2023
75a061e
ActionAnnotationToAttributeRector now also parses extra @Translate ar…
bbrala Dec 10, 2023
283d96b
Fix code-style
bbrala Dec 10, 2023
98faa8d
Refactor some methods in AbstractDrupalCoreRector
bbrala Dec 11, 2023
331b631
Fix some logic in AbstractDrupalCoreRector so its more readable (and …
bbrala Dec 11, 2023
9922589
Introduce DrupalIntroducedAndRemovalVersionConfiguration and refactor…
bbrala Dec 11, 2023
6dad267
Add tests for BC path and update default tests to expect no BC path
bbrala Dec 11, 2023
651332f
Fix convertTranslateAnnotation early return. Also simplify a little b…
bbrala Dec 11, 2023
773255a
Fix style
bbrala Jan 14, 2024
f249f01
Remove prefixed class from use statements.
bbrala Mar 8, 2024
262dffa
Allow rule to be configured so we can use it on multiple rules. Renam…
bbrala Mar 8, 2024
8f0feda
Rename fixtures to add plugin id
bbrala Mar 8, 2024
58566af
Add block test and configuration
bbrala Mar 8, 2024
ce8ad53
Add missing deriver key
bbrala Mar 8, 2024
fc50d58
Use built in AnnotationToAttribute mapper for forms value in Block an…
bbrala Mar 8, 2024
0d26dd5
Fix codestyle
bbrala Mar 8, 2024
85f4742
Fully remove annotations from drupal 10 set for now until we have bet…
bbrala Mar 8, 2024
12ebdc7
Protected to public
bbrala Mar 8, 2024
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
11 changes: 11 additions & 0 deletions config/drupal-10/drupal-10.2-deprecations.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

declare(strict_types=1);

use DrupalRector\Drupal10\Rector\Deprecation\AnnotationToAttributeRector;
use DrupalRector\Drupal10\Rector\ValueObject\AnnotationToAttributeConfiguration;
use DrupalRector\Rector\Deprecation\FunctionToStaticRector;
use DrupalRector\Rector\Deprecation\MethodToMethodWithCheckRector;
use DrupalRector\Rector\ValueObject\FunctionToStaticConfiguration;
Expand All @@ -24,4 +26,13 @@
new MethodToMethodWithCheckConfiguration('Drupal\system\Plugin\ImageToolkit\GDToolkit', 'getResource', 'getImage'),
new MethodToMethodWithCheckConfiguration('Drupal\system\Plugin\ImageToolkit\GDToolkit', 'setResource', 'setImage'),
]);

// @see https://www.drupal.org/node/3395575
$rectorConfig->ruleWithConfiguration(AnnotationToAttributeRector::class, [
new AnnotationToAttributeConfiguration('10.2.0', '12.0.0', 'Action', 'Drupal\Core\Action\Attribute\Action'),
]);
// This rule is disabled from now to first see how it performs on core.
$rectorConfig->skip([
AnnotationToAttributeRector::class,
]);
};
282 changes: 282 additions & 0 deletions src/Drupal10/Rector/Deprecation/AnnotationToAttributeRector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,282 @@
<?php

declare(strict_types=1);

namespace DrupalRector\Drupal10\Rector\Deprecation;

use DrupalRector\Contract\VersionedConfigurationInterface;
use DrupalRector\Drupal10\Rector\ValueObject\AnnotationToAttributeConfiguration;
use DrupalRector\Rector\AbstractDrupalCoreRector;
use DrupalRector\Rector\ValueObject\DrupalIntroducedVersionConfiguration;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Attribute;
use PhpParser\Node\AttributeGroup;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode;
use Rector\BetterPhpDocParser\PhpDoc\ArrayItemNode;
use Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
use Rector\BetterPhpDocParser\PhpDocInfo\TokenIteratorFactory;
use Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTagRemover;
use Rector\BetterPhpDocParser\PhpDocParser\StaticDoctrineAnnotationParser\ArrayParser;
use Rector\Comments\NodeDocBlock\DocBlockUpdater;
use Rector\PhpAttribute\AnnotationToAttributeMapper;
use Rector\ValueObject\PhpVersion;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @changelog https://docs.phpunit.de/en/10.0/annotations.html#ticket
*
* @see \Rector\PHPUnit\Tests\AnnotationsToAttributes\Rector\Class_\TicketAnnotationToAttributeRector\TicketAnnotationToAttributeRectorTest
*/
final class AnnotationToAttributeRector extends AbstractDrupalCoreRector implements MinPhpVersionInterface
{
/**
* @var array|AnnotationToAttributeConfiguration[]
*/
protected array $configuration = [];

private PhpDocTagRemover $phpDocTagRemover;

private DocBlockUpdater $docBlockUpdater;

private ArrayParser $arrayParser;

private TokenIteratorFactory $tokenIteratorFactory;

private PhpDocInfoFactory $phpDocInfoFactory;

/**
* @var AnnotationToAttributeMapper
*/
private AnnotationToAttributeMapper $annotationToAttributeMapper;

public function __construct(PhpDocTagRemover $phpDocTagRemover, DocBlockUpdater $docBlockUpdater, PhpDocInfoFactory $phpDocInfoFactory, ArrayParser $arrayParser, TokenIteratorFactory $tokenIteratorFactory, AnnotationToAttributeMapper $annotationToAttributeMapper)
{
$this->phpDocTagRemover = $phpDocTagRemover;
$this->docBlockUpdater = $docBlockUpdater;
$this->phpDocInfoFactory = $phpDocInfoFactory;
$this->arrayParser = $arrayParser;
$this->tokenIteratorFactory = $tokenIteratorFactory;
$this->annotationToAttributeMapper = $annotationToAttributeMapper;
}

public function configure(array $configuration): void
{
foreach ($configuration as $value) {
if (!($value instanceof AnnotationToAttributeConfiguration)) {
throw new \InvalidArgumentException(sprintf('Each configuration item must be an instance of "%s"', DrupalIntroducedVersionConfiguration::class));
}
}

parent::configure($configuration);
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Change annotations with value to attribute', [new CodeSample(<<<'CODE_SAMPLE'

namespace Drupal\Core\Action\Plugin\Action;

use Drupal\Core\Session\AccountInterface;

/**
* Publishes an entity.
*
* @Action(
* id = "entity:publish_action",
* action_label = @Translation("Publish"),
* deriver = "Drupal\Core\Action\Plugin\Action\Derivative\EntityPublishedActionDeriver",
* )
*/
class PublishAction extends EntityActionBase {
CODE_SAMPLE
, <<<'CODE_SAMPLE'

namespace Drupal\Core\Action\Plugin\Action;

use Drupal\Core\Action\Plugin\Action\Derivative\EntityPublishedActionDeriver;
use Drupal\Core\Action\Attribute\Action;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
* Publishes an entity.
*/
#[Action(
id: 'entity:publish_action',
action_label: new TranslatableMarkup('Publish'),
deriver: EntityPublishedActionDeriver::class
)]
class PublishAction extends EntityActionBase {
CODE_SAMPLE
)]);
}

/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Class_::class];
}

public function provideMinPhpVersion(): int
{
return PhpVersion::PHP_81;
}

/**
* @param Class_|ClassMethod $node
*/
public function refactor(Node $node): ?Node
{
foreach ($this->configuration as $configuration) {
if ($this->rectorShouldApplyToDrupalVersion($configuration) === false) {
continue;
}

$result = $this->refactorWithConfiguration($node, $configuration);

// Skip if no result.
if ($result === null) {
continue;
}

return $result;
}

return null;
}

/**
* @param Class_|ClassMethod $node
* @param AnnotationToAttributeConfiguration $configuration
*/
public function refactorWithConfiguration(Node $node, VersionedConfigurationInterface $configuration): ?Node
{
$phpDocInfo = $this->phpDocInfoFactory->createFromNode($node);
if (!$phpDocInfo instanceof PhpDocInfo) {
return null;
}

$tagsByName = $phpDocInfo->getTagsByName($configuration->getAnnotation());
if ($tagsByName === []) {
return null;
}

$hasAttribute = false;
foreach ($node->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
if ($attr->name->toString() === $configuration->getAttributeClass()) {
$hasAttribute = true;
break 2;
}
}
}

$docBlockHasChanged = \false;
foreach ($tagsByName as $valueNode) {
if (!$valueNode->value instanceof GenericTagValueNode) {
continue;
}

if ($hasAttribute === false) {
$stringValue = $valueNode->value->value;
$stringValue = '{'.trim($stringValue, '()').'}';
$tokenIterator = $this->tokenIteratorFactory->create($stringValue);
$data = $this->arrayParser->parseCurlyArray($tokenIterator, $node);
$attribute = $this->createAttribute($configuration->getAttributeClass(), $data);
$node->attrGroups[] = new AttributeGroup([$attribute]);
}
Comment on lines +191 to +198
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can this do a better check that the annotation matching the ending class name?

Wouldn't this cause @foo to become #Foo attribute because its a generic string?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Do you mean here; you get to this code after checking a tag is present as configured. Then we move on to check if there is already an attribute. If that is present, then we loopt through the tagnames and if there was no attribute matching the relevant attribute class from the configuration we start building the attribute based on the class passed into the rector by the configuration.

Don't really see how you could break this, unless user error using their own config?

Copy link
Collaborator

Choose a reason for hiding this comment

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

More so just:

$blah = explode('\', $configuration->getAttributeClass());
$className = end($blah);
if ($blah === substr($stringValue, 1)) {

Not entirely configured. Just that the tag matches the attribute's class name. I'm going to bet there is a "malformed" phpdoc somewhere with what the phpdoc parser considers generic tags


if (version_compare($this->installedDrupalVersion(), $configuration->getRemoveVersion(), '>=')) {
$this->phpDocTagRemover->removeTagValueFromNode($phpDocInfo, $valueNode);
$docBlockHasChanged = \true;
}
}
if ($docBlockHasChanged) {
$this->docBlockUpdater->updateRefactoredNodeWithPhpDocInfo($node);

return $node;
}

return null;
}

/**
* @param array|ArrayItemNode[] $parsedArgs
*
* @return Attribute
*/
private function createAttribute(string $attributeClass, array $parsedArgs): Attribute
{
$fullyQualified = new FullyQualified($attributeClass);
$args = [];
foreach ($parsedArgs as $value) {
if ($value->key == 'deriver') {
$arg = $this->nodeFactory->createClassConstFetch($value->value->value, 'class');
} elseif ($value->value instanceof DoctrineAnnotationTagValueNode) {
$arg = $this->convertTranslateAnnotation($value->value);
} elseif ($value->key === 'forms') {
$attribute = $this->annotationToAttributeMapper->map($value);
$arg = $attribute->value;
} else {
$arg = new String_($value->value->value);
}

$args[] = new Arg($arg, \false, \false, [], new Node\Identifier($value->key));
}

return new Attribute($fullyQualified, $args);
}

public function convertTranslateAnnotation(DoctrineAnnotationTagValueNode $value): ?Node\Expr\New_
{
// Check the annotation type, this will be helpful later.
if ($value->identifierTypeNode->name !== '@Translation') {
return null;
}

$valueArg = null;
$argumentArg = null;
$contextArg = null;

// Loop through the values of the annotation, just to make 100% sure we have the correct argument order
foreach ($value->values as $translateValue) {
if ($translateValue->key === null) {
$valueArg = $this->nodeFactory->createArg($translateValue->value->value);
}
if ($translateValue->key === 'context') {
$contextArg = $this->nodeFactory->createArg(['context' => $translateValue->value->value]);
}
if ($translateValue->key === 'arguments') {
$argumentArg = [];
foreach ($translateValue->value->values as $argumentValue) {
$argumentArg[$argumentValue->key->value] = $argumentValue->value->value;
}
$argumentArg = $this->nodeFactory->createArg($argumentArg);
}
}

$argArray = [];
if ($valueArg !== null) {
$argArray[] = $valueArg;
}
if ($argumentArg !== null) {
$argArray[] = $argumentArg;
}
if ($contextArg !== null) {
$argArray[] = $contextArg;
}

return new Node\Expr\New_(new Node\Name('Drupal\Core\StringTranslation\TranslatableMarkup'), $argArray);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

declare(strict_types=1);

namespace DrupalRector\Drupal10\Rector\ValueObject;

use DrupalRector\Contract\VersionedConfigurationInterface;

class AnnotationToAttributeConfiguration implements VersionedConfigurationInterface
{
private string $introducedVersion;

private string $removeVersion;

private string $annotation;

private string $attributeClass;

public function __construct(string $introducedVersion, string $removeVersion, string $annotation, string $attributeClass)
{
$this->introducedVersion = $introducedVersion;
$this->removeVersion = $removeVersion;
$this->annotation = $annotation;
$this->attributeClass = $attributeClass;
}

public function getIntroducedVersion(): string
{
return $this->introducedVersion;
}

public function getRemoveVersion(): string
{
return $this->removeVersion;
}

public function getAnnotation(): string
{
return $this->annotation;
}

public function getAttributeClass(): string
{
return $this->attributeClass;
}
}
Loading
Loading