From 9d310ce5daca61f51f35e3c8755a442998f1c536 Mon Sep 17 00:00:00 2001 From: Tomas Votruba Date: Sat, 13 Jan 2024 10:41:12 +0100 Subject: [PATCH] Skip null type in ReturnTypeFromStrictScalarReturnExprRector as often not desired (#5462) --- .../Fixture/skip_null_as_temporary.php.inc | 11 +++++++++++ .../Rector/Switch_/SingularSwitchToIfRector.php | 2 +- .../ReturnTypeFromStrictScalarReturnExprRector.php | 6 ++++++ 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 rules-tests/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictScalarReturnExprRector/Fixture/skip_null_as_temporary.php.inc diff --git a/rules-tests/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictScalarReturnExprRector/Fixture/skip_null_as_temporary.php.inc b/rules-tests/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictScalarReturnExprRector/Fixture/skip_null_as_temporary.php.inc new file mode 100644 index 00000000000..02726e20ef6 --- /dev/null +++ b/rules-tests/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictScalarReturnExprRector/Fixture/skip_null_as_temporary.php.inc @@ -0,0 +1,11 @@ +cond instanceof Expr) { // remove default clause because it cause syntax error - return array_filter($onlyCase->stmts, static fn(Stmt $stmt): bool => ! $stmt instanceof Break_); + return array_filter($onlyCase->stmts, static fn (Stmt $stmt): bool => ! $stmt instanceof Break_); } $if = new If_(new Identical($node->cond, $onlyCase->cond)); diff --git a/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictScalarReturnExprRector.php b/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictScalarReturnExprRector.php index 0e7e94fce5e..86119634767 100644 --- a/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictScalarReturnExprRector.php +++ b/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictScalarReturnExprRector.php @@ -10,6 +10,7 @@ use PhpParser\Node\Stmt\Function_; use PhpParser\Node\UnionType; use PHPStan\Analyser\Scope; +use PHPStan\Type\NullType; use PHPStan\Type\Type; use Rector\Contract\Rector\ConfigurableRectorInterface; use Rector\PHPStanStaticTypeMapper\Enum\TypeKind; @@ -117,6 +118,11 @@ public function refactorWithScope(Node $node, Scope $scope): ?Node return null; } + // skip null as often placeholder value and not an only type + if ($scalarReturnType instanceof NullType) { + return null; + } + $returnTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($scalarReturnType, TypeKind::RETURN); if (! $returnTypeNode instanceof Node) { return null;