[Feature] Add configurable InlineSimplePropertyAnnotationRector for inlining of simple annotations (#2070)

* [Feature] Add configurable InlineSimplePropertyAnnotationRector for inlining of simple annotations

* [Feature] CR fix - use AllowEmptyConfigurableRectorInterface

* [Feature] CR fix - ltrim @ if user provides it in configuration by accident

* [Feature] CR fix - Renaming in tests

Co-authored-by: Jiří Bok <jiri.bok@protonmail.com>
This commit is contained in:
dorrogeray 2022-04-14 10:06:16 +02:00 committed by GitHub
parent c509923516
commit d30a86313f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 491 additions and 1 deletions

View File

@ -8,7 +8,7 @@
- [CodeQuality](#codequality) (70)
- [CodingStyle](#codingstyle) (34)
- [CodingStyle](#codingstyle) (35)
- [Compatibility](#compatibility) (1)
@ -1917,6 +1917,47 @@ Refactor `func_get_args()` in to a variadic param
<br>
### InlineSimplePropertyAnnotationRector
Inline simple `@var` annotations (or other annotations) when they are the only thing in the phpdoc
:wrench: **configure it!**
- class: [`Rector\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector`](../rules/CodingStyle/Rector/Property/InlineSimplePropertyAnnotationRector.php)
```php
use Rector\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(InlineSimplePropertyAnnotationRector::class)
->configure(['var', 'phpstan-var']);
};
```
```diff
final class SomeClass
{
- /**
- * @phpstan-var string
- */
+ /** @phpstan-var string */
private const TEXT = 'text';
- /**
- * @var DateTime[]
- */
+ /** @var DateTime[]|null */
private ?array $dateTimes;
}
```
<br>
### MakeInheritedMethodVisibilitySameAsParentRector
Make method visibility same as parent one

View File

@ -0,0 +1,23 @@
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\CustomConfig;
final class InlineSimpleVarAnnotationWithCustomConfig
{
/**
* @custom-var \DateTime[]|null
*/
private ?array $dateTimes;
}
?>
-----
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\CustomConfig;
final class InlineSimpleVarAnnotationWithCustomConfig
{
/** @custom-var \DateTime[]|null */
private ?array $dateTimes;
}
?>

View File

@ -0,0 +1,12 @@
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\CustomConfig;
final class SkipUnconfiguredAnnotationWithCustomConfig
{
/**
* @var \DateTime[]|null A datetime!
*/
private ?array $dateTimes;
}
?>

View File

@ -0,0 +1,23 @@
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\EmptyConfig;
final class InlineSimpleVarAnnotation
{
/**
* @var \DateTime[]|null
*/
private ?array $dateTimes;
}
?>
-----
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\EmptyConfig;
final class InlineSimpleVarAnnotation
{
/** @var \DateTime[]|null */
private ?array $dateTimes;
}
?>

View File

@ -0,0 +1,39 @@
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\EmptyConfig;
final class InlineSimpleVarAnnotationAboveClassConstant
{
/**
* @var string[]
*/
private const AXES = ['x', 'y', 'z'];
/**
* @phpstan-var int[]
*/
public const NUMBERS = [1, 2, 3];
/**
* @psalm-var \DateTime[]|null
*/
private ?array $dateTimes;
}
?>
-----
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\EmptyConfig;
final class InlineSimpleVarAnnotationAboveClassConstant
{
/** @var string[] */
private const AXES = ['x', 'y', 'z'];
/** @phpstan-var int[] */
public const NUMBERS = [1, 2, 3];
/** @psalm-var \DateTime[]|null */
private ?array $dateTimes;
}
?>

View File

@ -0,0 +1,23 @@
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\EmptyConfig;
final class InlineSimpleVarAnnotationAboveClassConstant
{
/**
* @var string[]
*/
private const AXES = ['x', 'y', 'z'];
}
?>
-----
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\EmptyConfig;
final class InlineSimpleVarAnnotationAboveClassConstant
{
/** @var string[] */
private const AXES = ['x', 'y', 'z'];
}
?>

View File

@ -0,0 +1,23 @@
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\EmptyConfig;
final class InlineSimpleVarAnnotationWithComment
{
/**
* @var \DateTime[]|null A datetime!
*/
private ?array $dateTimes;
}
?>
-----
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\EmptyConfig;
final class InlineSimpleVarAnnotationWithComment
{
/** @var \DateTime[]|null A datetime! */
private ?array $dateTimes;
}
?>

View File

@ -0,0 +1,12 @@
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\EmptyConfig;
final class SkipUnconfiguredAnnotation
{
/**
* @unconfiguredAnnotation \DateTime[]|null A datetime!
*/
private ?array $dateTimes;
}
?>

View File

@ -0,0 +1,13 @@
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\EmptyConfig;
final class InlineVarAnnotationWithMultilineComment
{
/**
* @var \DateTime[]|null A datetime with multiline
* description!
*/
private ?array $dateTimes;
}
?>

View File

@ -0,0 +1,18 @@
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\EmptyConfig;
final class InlineVarAnnotationWithinComplexComment
{
/**
* @Serializer\VirtualProperty
* @Serializer\Type("array<DateTime>")
* @Assert\All({
* @Assert\NotBlank,
* @AppAssert\Country,
* })
* @var \DateTime[] $dateTimes
*/
private array $dateTimes;
}
?>

View File

@ -0,0 +1,25 @@
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\EmptyConfig;
final class SkipVarTypesWhichBreakOnStringification
{
/**
* @phpstan-var 'week'|'month'|'year'
*/
private string $interval;
}
?>
-----
<?php
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\Fixture\EmptyConfig;
final class SkipVarTypesWhichBreakOnStringification
{
/**
* @phpstan-var 'week'|'month'|'year'
*/
private string $interval;
}
?>

View File

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector;
use Iterator;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
use Symplify\SmartFileSystem\SmartFileInfo;
final class InlineSimplePropertyAnnotationRectorTest extends AbstractRectorTestCase
{
/**
* @dataProvider provideData()
*/
public function test(SmartFileInfo $fileInfo): void
{
$this->doTestFileInfo($fileInfo);
}
/**
* @return Iterator<SmartFileInfo>
*/
public function provideData(): Iterator
{
return $this->yieldFilesFromDirectory(__DIR__ . '/Fixture/EmptyConfig');
}
public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configure_rule_empty_config.php';
}
}

View File

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector;
use Iterator;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
use Symplify\SmartFileSystem\SmartFileInfo;
final class InlineSimplePropertyAnnotationWithCustomConfigRectorTest extends AbstractRectorTestCase
{
/**
* @dataProvider provideData()
*/
public function test(SmartFileInfo $fileInfo): void
{
$this->doTestFileInfo($fileInfo);
}
/**
* @return Iterator<SmartFileInfo>
*/
public function provideData(): Iterator
{
return $this->yieldFilesFromDirectory(__DIR__ . '/Fixture/CustomConfig');
}
public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configure_rule_custom_config.php';
}
}

View File

@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector;
use Rector\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$rectorServiceConfigurator = $services->set(InlineSimplePropertyAnnotationRector::class);
/** @phpstan-ignore-next-line */
$rectorServiceConfigurator->configure(['custom-var']);
};

View File

@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector;
use Rector\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(InlineSimplePropertyAnnotationRector::class);
};

View File

@ -0,0 +1,144 @@
<?php
declare(strict_types=1);
namespace Rector\CodingStyle\Rector\Property;
use PhpParser\Comment\Doc;
use PhpParser\Node;
use PhpParser\Node\Stmt\ClassConst;
use PhpParser\Node\Stmt\Property;
use Rector\Core\Contract\Rector\AllowEmptyConfigurableRectorInterface;
use Rector\Core\Rector\AbstractRector;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use Webmozart\Assert\Assert;
/**
* @see \Rector\Tests\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector\InlineSimplePropertyAnnotationRectorTest
*/
final class InlineSimplePropertyAnnotationRector extends AbstractRector implements AllowEmptyConfigurableRectorInterface
{
/**
* @var string[]
*/
private array $annotationsToConsiderForInlining = ['@var', '@phpstan-var', '@psalm-var'];
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Inline simple @var annotations (or other annotations) when they are the only thing in the phpdoc',
[
new ConfiguredCodeSample(
<<<'CODE_SAMPLE'
final class SomeClass
{
/**
* @phpstan-var string
*/
private const TEXT = 'text';
/**
* @var DateTime[]
*/
private ?array $dateTimes;
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
final class SomeClass
{
/** @phpstan-var string */
private const TEXT = 'text';
/** @var DateTime[]|null */
private ?array $dateTimes;
}
CODE_SAMPLE
,
['var', 'phpstan-var'],
),
]
);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Property::class, ClassConst::class];
}
/**
* @param mixed[] $configuration
*/
public function configure(array $configuration): void
{
Assert::allString($configuration);
$this->annotationsToConsiderForInlining = array_map(
fn (string $annotation): string => '@' . ltrim($annotation, '@'),
$configuration
);
}
/**
* @param Property|ClassConst $node
*/
public function refactor(Node $node): ?Node
{
if ($this->shouldSkipNode($node)) {
return null;
}
$comments = $node->getAttribute(AttributeKey::COMMENTS, []);
if ((is_countable($comments) ? count($comments) : 0) !== 1) {
return null;
}
$phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node);
$phpDocNode = $phpDocInfo->getPhpDocNode();
$tags = $phpDocNode->getTags();
if (count($tags) !== 1) {
return null;
}
$tag = $tags[0];
if (! in_array($tag->name, $this->annotationsToConsiderForInlining, true)) {
return null;
}
if (str_contains((string) $tag, "\n")) {
return null;
}
// Handle edge cases where stringified tag is not same as it was originally
/** @var Doc $comment */
$comment = $comments[0];
if (! str_contains($comment->getText(), (string) $tag)) {
return null;
}
// Creating new node is the only way to enforce the "singleLined" property AFAIK
$newPhpDocInfo = $this->phpDocInfoFactory->createEmpty($node);
$newPhpDocInfo->makeSingleLined();
$newPhpDocNode = $newPhpDocInfo->getPhpDocNode();
$newPhpDocNode->children = [$tag];
return $node;
}
private function shouldSkipNode(ClassConst|Property $node): bool
{
if ($node instanceof Property && count($node->props) !== 1) {
return true;
}
return $node instanceof ClassConst && count($node->consts) !== 1;
}
}