[Feature] Add ReturnAnnotationIncorrectNullableRector for fixing incorrect null type in @return (#2060)

Co-authored-by: Jiří Bok <jiri.bok@protonmail.com>
This commit is contained in:
dorrogeray 2022-04-12 08:52:34 +02:00 committed by GitHub
parent 1fc2825e17
commit a1ac1b6fdf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 643 additions and 7 deletions

View File

@ -1,4 +1,4 @@
# 508 Rules Overview
# 510 Rules Overview
<br>
@ -86,9 +86,9 @@
- [Strict](#strict) (5)
- [Transform](#transform) (35)
- [Transform](#transform) (36)
- [TypeDeclaration](#typedeclaration) (24)
- [TypeDeclaration](#typedeclaration) (25)
- [Visibility](#visibility) (3)
@ -10195,6 +10195,43 @@ return static function (ContainerConfigurator $containerConfigurator): void {
<br>
### FileGetContentsAndJsonDecodeToStaticCallRector
Merge 2 function calls to static call
:wrench: **configure it!**
- class: [`Rector\Transform\Rector\FunctionLike\FileGetContentsAndJsonDecodeToStaticCallRector`](../rules/Transform/Rector/FunctionLike/FileGetContentsAndJsonDecodeToStaticCallRector.php)
```php
use Rector\Transform\Rector\FunctionLike\FileGetContentsAndJsonDecodeToStaticCallRector;
use Rector\Transform\ValueObject\StaticCallRecipe;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(FileGetContentsAndJsonDecodeToStaticCallRector::class)
->configure([new StaticCallRecipe('FileLoader', 'loadJson')]);
};
```
```diff
final class SomeClass
{
public function load($filePath)
{
- $fileGetContents = file_get_contents($filePath);
- return json_decode($fileGetContents, true);
+ return FileLoader::loadJson($filePath);
}
}
```
<br>
### FuncCallToConstFetchRector
Changes use of function calls to use constants
@ -11702,6 +11739,28 @@ Add `@var` to properties that are missing it
<br>
### ReturnAnnotationIncorrectNullableRector
Add or remove null type from `@return` phpdoc typehint based on php return type declaration
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector`](../rules/TypeDeclaration/Rector/ClassMethod/ReturnAnnotationIncorrectNullableRector.php)
```diff
final class SomeClass
{
/**
- * @return \DateTime[]
+ * @return \DateTime[]|null
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}
```
<br>
### ReturnNeverTypeRector
Add "never" return-type for methods that never return anything

View File

@ -0,0 +1,14 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnAnnotationAlreadyIncludesNull
{
/**
* @return \DateTime[]|null
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}

View File

@ -0,0 +1,43 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnAnnotationComplex
{
/**
* @Serializer\VirtualProperty
* @Serializer\Type("array<DateTime>")
* @Assert\All({
* @Assert\NotBlank,
* @AppAssert\Country,
* })
* @return \DateTime[]
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnAnnotationComplex
{
/**
* @Serializer\VirtualProperty
* @Serializer\Type("array<DateTime>")
* @Assert\All({
* @Assert\NotBlank,
* @AppAssert\Country,
* })
* @return \DateTime[]|null
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}
?>

View File

@ -0,0 +1,31 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnAnnotationIncorrectlyIncludesNullOnScalar
{
/**
* @return string|null
*/
public function getDateTimes(): array
{
return $this->text;
}
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnAnnotationIncorrectlyIncludesNullOnScalar
{
/**
* @return string
*/
public function getDateTimes(): array
{
return $this->text;
}
}
?>

View File

@ -0,0 +1,31 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnAnnotationIncorrectlyIncludesNull
{
/**
* @return \DateTime[]|null
*/
public function getDateTimes(): array
{
return $this->dateTimes;
}
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnAnnotationIncorrectlyIncludesNull
{
/**
* @return \DateTime[]
*/
public function getDateTimes(): array
{
return $this->dateTimes;
}
}
?>

View File

@ -0,0 +1,37 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnAnnotationIsMissingNullWithGenericSyntax
{
/**
* Rector automatically transforms generic int-keyed simple arrays to the [] notation
* @see \Rector\PHPStanStaticTypeMapper\TypeMapper\ArrayTypeMapper::isIntegerKeyAndNonNestedArray
*
* @return array<int,\DateTime>
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnAnnotationIsMissingNullWithGenericSyntax
{
/**
* Rector automatically transforms generic int-keyed simple arrays to the [] notation
* @see \Rector\PHPStanStaticTypeMapper\TypeMapper\ArrayTypeMapper::isIntegerKeyAndNonNestedArray
*
* @return \DateTime[]|null
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}
?>

View File

@ -0,0 +1,31 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnAnnotationIsMissingNullWithNestedGenericSyntax
{
/**
* @return array<int, array<string, \DateTime>>
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnAnnotationIsMissingNullWithNestedGenericSyntax
{
/**
* @return array<int, array<string, \DateTime>>|null
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}
?>

View File

@ -0,0 +1,31 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnAnnotationIsMissingNull
{
/**
* @return \DateTime[]
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnAnnotationIsMissingNull
{
/**
* @return \DateTime[]|null
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}
?>

View File

@ -0,0 +1,27 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
/**
* @return \DateTime[]|null
*/
function getDateTimes(): array
{
return [new \DateTime()];
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
/**
* @return \DateTime[]
*/
function getDateTimes(): array
{
return [new \DateTime()];
}
?>

View File

@ -0,0 +1,27 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
/**
* @return \DateTime[]
*/
function getDateTimes(int $i): ?array
{
return $i > 0 ? [new \DateTime()] : null;
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
/**
* @return \DateTime[]|null
*/
function getDateTimes(int $i): ?array
{
return $i > 0 ? [new \DateTime()] : null;
}
?>

View File

@ -0,0 +1,31 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnUnionAnnotationIncorrectlyIncludesNull
{
/**
* @return \DateTime[]|\DateTimeImmutable[]|null
*/
public function getDateTimes(): array
{
return $this->dateTimes;
}
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnUnionAnnotationIncorrectlyIncludesNull
{
/**
* @return \DateTime[]|\DateTimeImmutable[]
*/
public function getDateTimes(): array
{
return $this->dateTimes;
}
}
?>

View File

@ -0,0 +1,31 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnUnionAnnotationMissingNull
{
/**
* @return \DateTime[]|\DateTimeImmutable[]
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class ReturnUnionAnnotationMissingNull
{
/**
* @return \DateTime[]|\DateTimeImmutable[]|null
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}
?>

View File

@ -0,0 +1,12 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class SkipBrokenReturnAnnotation
{
/** @return # */
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class SkipReturnAnnotationComplexOnPhpdocParserFailure
{
/**
* @Serializer\VirtualProperty
* @Serializer\Type("array<DateTime>")
* @Assert\All({
* @Assert\NotBlank,
* @AppAssert\Country
* })
* @return \DateTime[]
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class SkipReturnAnnotationWhenMethodHasNoReturnType
{
/**
* @return \DateTime[]
*/
public function getDateTimes()
{
return $this->dateTimes;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class SkipReturnAnnotationWhenPropertyHasNonNullableType
{
/**
* @return \DateTime[]
*/
public function getDateTimes(): array
{
return $this->dateTimes;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector\Fixture;
final class SkipReturnAnnotationWithGenericSyntaxWhenNullIsNotMissing
{
/**
* @return array<int,\DateTime>|null $dateTimes
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}

View File

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector;
use Iterator;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
use Symplify\SmartFileSystem\SmartFileInfo;
final class ReturnAnnotationIncorrectNullableRectorTest 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 Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnAnnotationIncorrectNullableRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ReturnAnnotationIncorrectNullableRector::class);
};

View File

@ -6,7 +6,7 @@ namespace Rector\TypeDeclaration\Guard;
use Nette\Utils\Strings;
use PhpParser\Comment\Doc;
use PhpParser\Node\Stmt\Property;
use PhpParser\Node;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
use Rector\NodeTypeResolver\Node\AttributeKey;
@ -28,14 +28,14 @@ final class PhpDocNestedAnnotationGuard
* 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
public function isPhpDocCommentCorrectlyParsed(Node $node): bool
{
$comments = $property->getAttribute(AttributeKey::COMMENTS, []);
$comments = $node->getAttribute(AttributeKey::COMMENTS, []);
if ((is_countable($comments) ? count($comments) : 0) !== 1) {
return true;
}
$phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property);
$phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node);
/** @var Doc $phpDoc */
$phpDoc = $comments[0];

View File

@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
namespace Rector\TypeDeclaration\Rector\ClassMethod;
use PhpParser\Node;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Function_;
use PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode;
use PHPStan\Type\Type;
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\ClassMethod\ReturnAnnotationIncorrectNullableRector\ReturnAnnotationIncorrectNullableRectorTest
*/
final class ReturnAnnotationIncorrectNullableRector 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 @return phpdoc typehint based on php return type declaration',
[
new CodeSample(
<<<'CODE_SAMPLE'
final class SomeClass
{
/**
* @return \DateTime[]
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
final class SomeClass
{
/**
* @return \DateTime[]|null
*/
public function getDateTimes(): ?array
{
return $this->dateTimes;
}
}
CODE_SAMPLE
),
]
);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [ClassMethod::class, Function_::class];
}
/**
* @param ClassMethod $node
*/
public function refactor(Node $node): ?Node
{
$returnType = $node->getReturnType();
if ($returnType === null) {
return null;
}
if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::TYPED_PROPERTIES)) {
return null;
}
if (! $this->phpDocNestedAnnotationGuard->isPhpDocCommentCorrectlyParsed($node)) {
return null;
}
$phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node);
$returnTagValueNode = $phpDocInfo->getReturnTagValue();
if (! $returnTagValueNode instanceof ReturnTagValueNode) {
return null;
}
$phpStanDocTypeNode = $returnTagValueNode->type;
$phpParserType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($returnType);
$docType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType($phpStanDocTypeNode, $node);
$updatedPhpDocType = $this->phpDocNullableTypeHelper->resolveUpdatedPhpDocTypeFromPhpDocTypeAndPhpParserType(
$docType,
$phpParserType
);
if (! $updatedPhpDocType instanceof Type) {
return null;
}
$this->phpDocTypeChanger->changeReturnType($phpDocInfo, $updatedPhpDocType);
if (! $phpDocInfo->hasChanged()) {
return null;
}
return $node;
}
}