Skip to content

Commit

Permalink
[TypeDeclaration] Add ReturnTypeFromReturnCastRector (#5905)
Browse files Browse the repository at this point in the history
* [TypeDeclaration] Add ReturnTypeFromReturnCastRector

* [TypeDeclaration] Add ReturnTypeFromReturnCastRector

* register

* only specific type

* final touch: skip no return

* skip multiple casts as union type and covered by ReturnUnionTypeRector

* [ci-review] Rector Rectify

---------

Co-authored-by: GitHub Action <actions@github.com>
  • Loading branch information
samsonasik and actions-user committed May 20, 2024
1 parent d1eb62e commit b8847be
Show file tree
Hide file tree
Showing 10 changed files with 338 additions and 5 deletions.
53 changes: 48 additions & 5 deletions build/target-repository/docs/rector_rules_overview.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# 374 Rules Overview
# 376 Rules Overview

<br>

## Categories

- [Arguments](#arguments) (4)

- [Carbon](#carbon) (3)
- [Carbon](#carbon) (4)

- [CodeQuality](#codequality) (75)

Expand Down Expand Up @@ -60,7 +60,7 @@

- [Transform](#transform) (25)

- [TypeDeclaration](#typedeclaration) (46)
- [TypeDeclaration](#typedeclaration) (47)

- [Visibility](#visibility) (3)

Expand Down Expand Up @@ -148,7 +148,7 @@ Replaces defined map of arguments in defined methods and their calls.

### DateFuncCallToCarbonRector

Convert `date()` function call to Carbon::*()
Convert `date()` function call to `Carbon::now()->format(*)`

- class: [`Rector\Carbon\Rector\FuncCall\DateFuncCallToCarbonRector`](../rules/Carbon/Rector/FuncCall/DateFuncCallToCarbonRector.php)

Expand All @@ -158,7 +158,7 @@ Convert `date()` function call to Carbon::*()
public function run()
{
- $date = date('Y-m-d');
+ $date = \Carbon\Carbon::now()->format('Y-m-d')
+ $date = \Carbon\Carbon::now()->format('Y-m-d');
}
}
```
Expand Down Expand Up @@ -197,6 +197,25 @@ Convert new `DateTime()` with a method call to Carbon::*()

<br>

### TimeFuncCallToCarbonRector

Convert `time()` function call to `Carbon::now()->timestamp`

- class: [`Rector\Carbon\Rector\FuncCall\TimeFuncCallToCarbonRector`](../rules/Carbon/Rector/FuncCall/TimeFuncCallToCarbonRector.php)

```diff
class SomeClass
{
public function run()
{
- $time = time();
+ $time = \Carbon\Carbon::now()->timestamp;
}
}
```

<br>

## CodeQuality

### AbsolutizeRequireAndIncludePathRector
Expand Down Expand Up @@ -7043,6 +7062,30 @@ Add "never" return-type for methods that never return anything

<br>

### ReturnTypeFromReturnCastRector

Add return type to function like with return cast

- class: [`Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnCastRector`](../rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromReturnCastRector.php)

```diff
final class SomeClass
{
- public function action($param)
+ public function action($param): array
{
try {
return (array) $param;
} catch (Exception $exception) {
// some logging
throw $exception;
}
}
}
```

<br>

### ReturnTypeFromReturnDirectArrayRector

Add return type from return direct array
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnCastRector\Fixture;

final class AddReturnArrayByCast
{
public function getArray($data)
{
try {
return (array) $data;
} catch (\Exception $e) {
throw $e;
}
}
}

?>
-----
<?php

declare(strict_types=1);

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnCastRector\Fixture;

final class AddReturnArrayByCast
{
public function getArray($data): array
{
try {
return (array) $data;
} catch (\Exception $e) {
throw $e;
}
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnCastRector\Fixture;

final class AddReturnObjectByCast
{
public function getObject($data)
{
try {
return (object) $data;
} catch (\Exception $e) {
throw $e;
}
}
}

?>
-----
<?php

declare(strict_types=1);

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnCastRector\Fixture;

final class AddReturnObjectByCast
{
public function getObject($data): \stdClass
{
try {
return (object) $data;
} catch (\Exception $e) {
throw $e;
}
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnCastRector\Fixture;

final class SkipMultipleCasts
{
public function run($data)
{
if (rand(0, 1)) {
return (string) $data;
}

return (bool) $data;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnCastRector\Fixture;

final class SkipNoReturn
{
public function run($data)
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnCastRector\Fixture;

final class SkipNotCasted
{
public function returnNotCasted($data)
{
try {
return $data;
} catch (\Exception $e) {
throw $e;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnCastRector;

use Iterator;
use PHPUnit\Framework\Attributes\DataProvider;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;

final class ReturnTypeFromReturnCastRectorTest extends AbstractRectorTestCase
{
#[DataProvider('provideData')]
public function test(string $filePath): void
{
$this->doTestFile($filePath);
}

public static function provideData(): Iterator
{
return self::yieldFilesFromDirectory(__DIR__ . '/Fixture');
}

public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configured_rule.php';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnCastRector;

return RectorConfig::configure()
->withRules([ReturnTypeFromReturnCastRector::class]);
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
<?php

declare(strict_types=1);

namespace Rector\TypeDeclaration\Rector\ClassMethod;

use PhpParser\Node;
use PhpParser\Node\Expr\Cast;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Function_;
use PhpParser\Node\Stmt\Return_;
use PHPStan\Analyser\Scope;
use PHPStan\Type\UnionType;
use Rector\PhpParser\Node\BetterNodeFinder;
use Rector\PHPStanStaticTypeMapper\Enum\TypeKind;
use Rector\Rector\AbstractScopeAwareRector;
use Rector\StaticTypeMapper\StaticTypeMapper;
use Rector\TypeDeclaration\TypeInferer\ReturnTypeInferer;
use Rector\ValueObject\PhpVersionFeature;
use Rector\VendorLocker\NodeVendorLocker\ClassMethodReturnTypeOverrideGuard;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnCastRector\ReturnTypeFromReturnCastRectorTest
*/
final class ReturnTypeFromReturnCastRector extends AbstractScopeAwareRector implements MinPhpVersionInterface
{
public function __construct(
private readonly ClassMethodReturnTypeOverrideGuard $classMethodReturnTypeOverrideGuard,
private readonly ReturnTypeInferer $returnTypeInferer,
private readonly BetterNodeFinder $betterNodeFinder,
private readonly StaticTypeMapper $staticTypeMapper
) {
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Add return type to function like with return cast', [
new CodeSample(
<<<'CODE_SAMPLE'
final class SomeClass
{
public function action($param)
{
try {
return (array) $param;
} catch (Exception $exception) {
// some logging
throw $exception;
}
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
final class SomeClass
{
public function action($param): array
{
try {
return (array) $param;
} catch (Exception $exception) {
// some logging
throw $exception;
}
}
}
CODE_SAMPLE
),
]);
}

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

/**
* @param ClassMethod|Function_|Closure $node
*/
public function refactorWithScope(Node $node, Scope $scope): ?Node
{
if ($node->returnType !== null) {
return null;
}

if ($node instanceof ClassMethod && $this->classMethodReturnTypeOverrideGuard->shouldSkipClassMethod(
$node,
$scope
)) {
return null;
}

$hasNonCastReturn = (bool) $this->betterNodeFinder->findFirstInFunctionLikeScoped(
$node,
static fn (Node $subNode): bool => $subNode instanceof Return_ && ! $subNode->expr instanceof Cast
);

if ($hasNonCastReturn) {
return null;
}

$returnType = $this->returnTypeInferer->inferFunctionLike($node);
if ($returnType instanceof UnionType || $returnType->isVoid()->yes()) {
return null;
}

$returnTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($returnType, TypeKind::RETURN);
if (! $returnTypeNode instanceof Node) {
return null;
}

$node->returnType = $returnTypeNode;
return $node;
}

public function provideMinPhpVersion(): int
{
return PhpVersionFeature::SCALAR_TYPES;
}
}

0 comments on commit b8847be

Please sign in to comment.