[Feature] Add VarAnnotationIncorrectNullableRector for fixing incorrect null type in @var (#2053)

* [Feature] Add VarAnnotationIncorrectNullableRector for fixing incorrect null type in @var

* [Feature] Code review fixes + Applied rector

Co-authored-by: Jiří Bok <jiri.bok@protonmail.com>
This commit is contained in:
dorrogeray 2022-04-11 15:02:33 +02:00 committed by GitHub
parent 20a5be338e
commit d4c5ec6dfa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 671 additions and 2 deletions

View File

@ -1,4 +1,4 @@
# 507 Rules Overview
# 508 Rules Overview
<br>
@ -88,7 +88,7 @@
- [Transform](#transform) (35)
- [TypeDeclaration](#typedeclaration) (23)
- [TypeDeclaration](#typedeclaration) (24)
- [Visibility](#visibility) (3)
@ -11871,6 +11871,25 @@ Complete property type based on getter strict types
<br>
### VarAnnotationIncorrectNullableRector
Add or remove null type from `@var` phpdoc typehint based on php property type declaration
- class: [`Rector\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector`](../rules/TypeDeclaration/Rector/Property/VarAnnotationIncorrectNullableRector.php)
```diff
final class SomeClass
{
/**
- * @var DateTime[]
+ * @var DateTime[]|null
*/
private ?array $dateTimes;
}
```
<br>
## Visibility
### ChangeConstantVisibilityRector

View File

@ -0,0 +1,9 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class SkipBrokenVarAnnotation
{
/** @phpstan-var 'week'|'month'|'year' */
private ?string $interval;
}

View File

@ -0,0 +1,21 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class SkipVarAnnotationComplexOnPhpdocParserFailure
{
/**
* Parser fails to interpret annotations when there is no comma after AppAssert\Country in Assert\All, this is likely a bug in rector or one
* of its dependencies. But we will skip these cases safely, so no worries.
*
* @OA\Property(property="countryCodes[]", default="null", example="CZ")
* @Serializer\Groups({"export"})
* @Assert\All({
* @Assert\NotBlank,
* @AppAssert\Country
* })
* @Serializer\Type("array<string>")
* @var string[]
*/
private ?array $countryCodes = null;
}

View File

@ -0,0 +1,11 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class SkipVarAnnotationWhenItAlreadyIncludesNull
{
/**
* @var \DateTime[]|null
*/
private ?array $dateTimes;
}

View File

@ -0,0 +1,11 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class SkipVarAnnotationWhenPropertyHasNoType
{
/**
* @var \DateTime[]
*/
private $dateTimes;
}

View File

@ -0,0 +1,11 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class SkipVarAnnotationWithGenericSyntaxWhenNullIsNotMissing
{
/**
* @var array<int,\DateTime>|null
*/
private ?array $dateTimes;
}

View File

@ -0,0 +1,39 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarAnnotationComplex
{
/**
* @OA\Property(property="countryCodes[]", default="null", example="CZ")
* @Serializer\Groups({"export"})
* @Serializer\Type("array<string>")
* @Assert\All({
* @Assert\NotBlank,
* @AppAssert\Country,
* })
* @var string[]
*/
private ?array $countryCodes = null;
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarAnnotationComplex
{
/**
* @OA\Property(property="countryCodes[]", default="null", example="CZ")
* @Serializer\Groups({"export"})
* @Serializer\Type("array<string>")
* @Assert\All({
* @Assert\NotBlank,
* @AppAssert\Country,
* })
* @var string[]|null
*/
private ?array $countryCodes = null;
}
?>

View File

@ -0,0 +1,25 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarAnnotationIncorrectlyIncludesNullOnScalar
{
/**
* @var string|null
*/
private string $text;
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarAnnotationIncorrectlyIncludesNullOnScalar
{
/**
* @var string
*/
private string $text;
}
?>

View File

@ -0,0 +1,25 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarAnnotationIncorrectlyIncludesNull
{
/**
* @var \DateTime[]|null
*/
private array $dateTimes;
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarAnnotationIncorrectlyIncludesNull
{
/**
* @var \DateTime[]
*/
private array $dateTimes;
}
?>

View File

@ -0,0 +1,31 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarAnnotationIsMissingNullWithGenericSyntax
{
/**
* Rector automatically transforms generic int-keyed simple arrays to the [] notation
* @see \Rector\PHPStanStaticTypeMapper\TypeMapper\ArrayTypeMapper::isIntegerKeyAndNonNestedArray
*
* @var array<int,\DateTime>
*/
private ?array $dateTimes;
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarAnnotationIsMissingNullWithGenericSyntax
{
/**
* Rector automatically transforms generic int-keyed simple arrays to the [] notation
* @see \Rector\PHPStanStaticTypeMapper\TypeMapper\ArrayTypeMapper::isIntegerKeyAndNonNestedArray
*
* @var \DateTime[]|null
*/
private ?array $dateTimes;
}
?>

View File

@ -0,0 +1,25 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarAnnotationIsMissingNullWithNestedGenericSyntax
{
/**
* @var array<int, array<string, \DateTime>>
*/
private ?array $dateTimes;
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarAnnotationIsMissingNullWithNestedGenericSyntax
{
/**
* @var array<int, array<string, \DateTime>>|null
*/
private ?array $dateTimes;
}
?>

View File

@ -0,0 +1,25 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarAnnotationIsMissingNull
{
/**
* @var \DateTime[]
*/
private ?array $dateTimes;
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarAnnotationIsMissingNull
{
/**
* @var \DateTime[]|null
*/
private ?array $dateTimes;
}
?>

View File

@ -0,0 +1,25 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarUnionAnnotationIncorrectlyIncludesNull
{
/**
* @var \DateTime[]|\DateTimeImmutable[]|null
*/
private array $dateTimes;
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarUnionAnnotationIncorrectlyIncludesNull
{
/**
* @var \DateTime[]|\DateTimeImmutable[]
*/
private array $dateTimes;
}
?>

View File

@ -0,0 +1,25 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarUnionAnnotationMissingNull
{
/**
* @var \DateTime[]|\DateTimeImmutable[]
*/
private ?array $dateTimes;
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\Fixture;
final class VarUnionAnnotationMissingNull
{
/**
* @var \DateTime[]|\DateTimeImmutable[]|null
*/
private ?array $dateTimes;
}
?>

View File

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector;
use Iterator;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
use Symplify\SmartFileSystem\SmartFileInfo;
final class VarAnnotationIncorrectNullableRectorTest 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');
}
public function provideConfigFilePath(): string
{
return __DIR__ . '/config/config.php';
}
}

View File

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

View File

@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace Rector\TypeDeclaration\Guard;
use Nette\Utils\Strings;
use PhpParser\Comment\Doc;
use PhpParser\Node\Stmt\Property;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
use Rector\NodeTypeResolver\Node\AttributeKey;
final class PhpDocNestedAnnotationGuard
{
/**
* Regex is used to count annotations including nested annotations
*
* @see https://regex101.com/r/G7wODT/1
* @var string
*/
private const SIMPLE_ANNOTATION_REGEX = '/@[A-z]+\(?/i';
public function __construct(private readonly PhpDocInfoFactory $phpDocInfoFactory)
{
}
/**
* Check if rector accidentally skipped annotation during parsing which it should not have (this bug is likely related to parsing of annotations
* in phpstan / rector)
*/
public function isPhpDocCommentCorrectlyParsed(Property $property): bool
{
$comments = $property->getAttribute(AttributeKey::COMMENTS, []);
if ((is_countable($comments) ? count($comments) : 0) !== 1) {
return true;
}
$phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property);
/** @var Doc $phpDoc */
$phpDoc = $comments[0];
$originalPhpDocText = $phpDoc->getText();
/**
* This is a safeguard to skip cases where the PhpStan / Rector phpdoc parser parses annotations incorrectly (ie.: nested annotations)
*/
$parsedPhpDocText = (string) $phpDocInfo->getPhpDocNode();
return ! $this->hasAnnotationCountChanged($originalPhpDocText, $parsedPhpDocText);
}
public function hasAnnotationCountChanged(string $originalPhpDocText, string $updatedPhpDocText): bool
{
$originalAnnotationCount = count(Strings::matchAll($originalPhpDocText, self::SIMPLE_ANNOTATION_REGEX));
$reconstructedAnnotationCount = count(Strings::matchAll($updatedPhpDocText, self::SIMPLE_ANNOTATION_REGEX));
return $originalAnnotationCount !== $reconstructedAnnotationCount;
}
}

View File

@ -0,0 +1,122 @@
<?php
declare(strict_types=1);
namespace Rector\TypeDeclaration\Helper;
use PhpParser\Node\Expr\ConstFetch;
use PhpParser\Node\Param;
use PHPStan\Type\NullType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;
use Rector\Core\PhpParser\Node\Value\ValueResolver;
use Rector\StaticTypeMapper\StaticTypeMapper;
final class PhpDocNullableTypeHelper
{
public function __construct(
private readonly StaticTypeMapper $staticTypeMapper,
private readonly ValueResolver $valueResolver
) {
}
/**
* @return Type|null Returns null if it was not possible to resolve new php doc type or if update is not required
*/
public function resolveUpdatedPhpDocTypeFromPhpDocTypeAndPhpParserType(
Type $phpDocType,
Type $phpParserType
): ?Type {
return $this->resolveUpdatedPhpDocTypeFromPhpDocTypeAndPhpParserTypeNullInfo(
$phpDocType,
$this->isParserTypeContainingNullType($phpParserType)
);
}
/**
* @return Type|null Returns null if it was not possible to resolve new php doc param type or if update is not required
*/
public function resolveUpdatedPhpDocTypeFromPhpDocTypeAndParamNode(Type $phpDocType, Param $param): ?Type
{
if ($param->type === null) {
return null;
}
$phpParserType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type);
if ($phpParserType instanceof UnionType) {
$isPhpParserTypeContainingNullType = TypeCombinator::containsNull($phpParserType);
} elseif ($param->default !== null) {
$value = $this->valueResolver->getValue($param->default);
$isPhpParserTypeContainingNullType = $value === null || ($param->default instanceof ConstFetch && $value === 'null');
} else {
$isPhpParserTypeContainingNullType = false;
}
return $this->resolveUpdatedPhpDocTypeFromPhpDocTypeAndPhpParserTypeNullInfo(
$phpDocType,
$isPhpParserTypeContainingNullType
);
}
private function isItRequiredToRemoveOrAddNullTypeToUnion(
bool $phpDocTypeContainsNullType,
bool $phpParserTypeContainsNullType,
): bool {
return ($phpParserTypeContainsNullType && ! $phpDocTypeContainsNullType) || (! $phpParserTypeContainsNullType && $phpDocTypeContainsNullType);
}
/**
* @param Type[] $updatedDocTypes
*/
private function composeUpdatedPhpDocType(array $updatedDocTypes): Type
{
return count($updatedDocTypes) === 1
? $updatedDocTypes[0]
: new UnionType($updatedDocTypes);
}
private function isParserTypeContainingNullType(Type $phpParserType): bool
{
if ($phpParserType instanceof UnionType) {
return TypeCombinator::containsNull($phpParserType);
}
return false;
}
private function resolveUpdatedPhpDocTypeFromPhpDocTypeAndPhpParserTypeNullInfo(
Type $phpDocType,
bool $isPhpParserTypeContainingNullType
): ?Type {
/** @var array<(NullType | UnionType)> $updatedDocTypes */
$updatedDocTypes = [];
$phpDocTypeContainsNullType = false;
if ($phpDocType instanceof UnionType) {
$phpDocTypeContainsNullType = TypeCombinator::containsNull($phpDocType);
foreach ($phpDocType->getTypes() as $subType) {
if ($subType instanceof NullType) {
continue;
}
$updatedDocTypes[] = $subType;
}
} else {
$updatedDocTypes[] = $phpDocType;
}
if (! $this->isItRequiredToRemoveOrAddNullTypeToUnion(
$phpDocTypeContainsNullType,
$isPhpParserTypeContainingNullType
)) {
return null;
}
if ($isPhpParserTypeContainingNullType) {
$updatedDocTypes[] = new NullType();
}
return $this->composeUpdatedPhpDocType($updatedDocTypes);
}
}

View File

@ -0,0 +1,140 @@
<?php
declare(strict_types=1);
namespace Rector\TypeDeclaration\Rector\Property;
use PhpParser\Node;
use PhpParser\Node\Stmt\Property;
use PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode;
use PHPStan\Type\MixedType;
use PHPStan\Type\Type;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo;
use Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTypeChanger;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\ValueObject\PhpVersionFeature;
use Rector\TypeDeclaration\Guard\PhpDocNestedAnnotationGuard;
use Rector\TypeDeclaration\Helper\PhpDocNullableTypeHelper;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\Tests\TypeDeclaration\Rector\Property\VarAnnotationIncorrectNullableRector\VarAnnotationIncorrectNullableRectorTest
*/
final class VarAnnotationIncorrectNullableRector extends AbstractRector
{
public function __construct(
private readonly PhpDocTypeChanger $phpDocTypeChanger,
private readonly PhpDocNullableTypeHelper $phpDocNullableTypeHelper,
private readonly PhpDocNestedAnnotationGuard $phpDocNestedAnnotationGuard
) {
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Add or remove null type from @var phpdoc typehint based on php property type declaration',
[
new CodeSample(
<<<'CODE_SAMPLE'
final class SomeClass
{
/**
* @var DateTime[]
*/
private ?array $dateTimes;
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
final class SomeClass
{
/**
* @var DateTime[]|null
*/
private ?array $dateTimes;
}
CODE_SAMPLE
),
]
);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Property::class];
}
/**
* @param Property $node
*/
public function refactor(Node $node): ?Node
{
if (count($node->props) !== 1) {
return null;
}
if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::TYPED_PROPERTIES)) {
return null;
}
if (! $this->phpDocNestedAnnotationGuard->isPhpDocCommentCorrectlyParsed($node)) {
return null;
}
$phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node);
if (! $this->isVarDocAlreadySet($phpDocInfo)) {
return null;
}
if ($node->type === null) {
return null;
}
$phpParserType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($node->type);
$varTagValueNode = $phpDocInfo->getVarTagValueNode();
if (! $varTagValueNode instanceof VarTagValueNode) {
return null;
}
if ($varTagValueNode->type === null) {
return null;
}
$docType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType($varTagValueNode->type, $node);
$updatedPhpDocType = $this->phpDocNullableTypeHelper->resolveUpdatedPhpDocTypeFromPhpDocTypeAndPhpParserType(
$docType,
$phpParserType
);
if (! $updatedPhpDocType instanceof Type) {
return null;
}
$this->phpDocTypeChanger->changeVarType($phpDocInfo, $updatedPhpDocType);
if (! $phpDocInfo->hasChanged()) {
return null;
}
return $node;
}
private function isVarDocAlreadySet(PhpDocInfo $phpDocInfo): bool
{
foreach (['@var', '@phpstan-var', '@psalm-var'] as $tagName) {
$varType = $phpDocInfo->getVarType($tagName);
if (! $varType instanceof MixedType) {
return true;
}
}
return false;
}
}