Skip to content

Commit

Permalink
[TypeDeclaration] Add ReturnTypeFromMockObjectRector
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba committed Jul 21, 2024
1 parent 8b72bde commit 48c3f4f
Show file tree
Hide file tree
Showing 7 changed files with 265 additions and 2 deletions.
24 changes: 22 additions & 2 deletions build/target-repository/docs/rector_rules_overview.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# 380 Rules Overview
# 381 Rules Overview

<br>

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

- [Transform](#transform) (25)

- [TypeDeclaration](#typedeclaration) (55)
- [TypeDeclaration](#typedeclaration) (56)

- [Visibility](#visibility) (3)

Expand Down Expand Up @@ -7110,6 +7110,26 @@ Add basic ? nullable type to class methods and functions, as of PHP 7.1

<br>

### ReturnTypeFromMockObjectRector

Add known property and return MockObject types

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

```diff
class SomeTest extends TestCase
{
- public function test()
+ public function test(): \PHPUnit\Framework\MockObject\MockObject
{
$someMock = $this->createMock(SomeClass::class);
return $someMock;
}
}
```

<br>

### ReturnTypeFromReturnCastRector

Add return type to function like with return cast
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

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

use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;

final class SkipFilledType extends TestCase
{
public function createMock(): MockObject
{
return $this->createMock('SomeType');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

declare(strict_types=1);

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

use PHPUnit\Framework\TestCase;

final class SomeTestWithMock extends TestCase
{
public function createMock()
{
return $this->createMock('SomeType');
}
}

?>
-----
<?php

declare(strict_types=1);

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

use PHPUnit\Framework\TestCase;

final class SomeTestWithMock extends TestCase
{
public function createMock(): \PHPUnit\Framework\MockObject\MockObject
{
return $this->createMock('SomeType');
}
}

?>
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\ReturnTypeFromMockObjectRector;

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

final class ReturnTypeFromMockObjectRectorTest 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\ReturnTypeFromMockObjectRector;

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

declare(strict_types=1);

namespace Rector\TypeDeclaration\Rector\ClassMethod;

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Stmt\ClassMethod;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\PhpParser\Node\BetterNodeFinder;
use Rector\Rector\AbstractRector;
use Rector\ValueObject\PhpVersionFeature;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromMockObjectRector\ReturnTypeFromMockObjectRectorTest
*/
final class ReturnTypeFromMockObjectRector extends AbstractRector implements MinPhpVersionInterface
{
/**
* @var string
*/
private const MOCK_OBJECT_CLASS = '̈́PHPUnit\Framework\MockObject\MockObject';

public function __construct(
private readonly BetterNodeFinder $betterNodeFinder
) {
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Add known property and return MockObject types', [
new CodeSample(
<<<'CODE_SAMPLE'
class SomeTest extends TestCase
{
public function test()
{
$someMock = $this->createMock(SomeClass::class);
return $someMock;
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class SomeTest extends TestCase
{
public function test(): \PHPUnit\Framework\MockObject\MockObject
{
$someMock = $this->createMock(SomeClass::class);
return $someMock;
}
}
CODE_SAMPLE
),

]);
}

public function getNodeTypes(): array
{
return [ClassMethod::class];
}

/**
* @param ClassMethod $node
*/
public function refactor(Node $node): ?Node
{
// type is already known
if ($node->returnType instanceof Node) {
return null;
}

if (! $this->isInsideTestCaseClass($node)) {
return null;
}

// we need exactly 1 return
$returns = $this->betterNodeFinder->findReturnsScoped($node);
if (count($returns) !== 1) {
return null;
}

$soleReturn = $returns[0];
if (! $soleReturn->expr instanceof Expr) {
return null;
}

$returnType = $this->getType($soleReturn->expr);
if (! $this->isMockObjectType($returnType)) {
return null;
}

$node->returnType = new FullyQualified(self::MOCK_OBJECT_CLASS);

return $node;
}

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

private function isIntersectionWithMockObjectType(Type $type): bool
{
if (! $type instanceof IntersectionType) {
return false;
}

if (count($type->getTypes()) !== 2) {
return false;
}

return in_array(MockObject::class, $type->getObjectClassNames());
}

private function isMockObjectType(Type $returnType): bool
{
if ($returnType instanceof ObjectType && $returnType->isInstanceOf(self::MOCK_OBJECT_CLASS)->yes()) {
return true;
}

return $this->isIntersectionWithMockObjectType($returnType);
}

private function isInsideTestCaseClass(ClassMethod $classMethod): bool
{
$scope = $classMethod->getAttribute(AttributeKey::SCOPE);
if (! $scope instanceof Scope) {
return false;
}

$classReflection = $scope->getClassReflection();
if (! $classReflection instanceof ClassReflection) {
return false;
}

// is phpunit test case?
return $classReflection->isSubclassOf(TestCase::class);
}
}
2 changes: 2 additions & 0 deletions src/Config/Level/TypeDeclarationLevel.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use Rector\TypeDeclaration\Rector\ClassMethod\ParamTypeByParentCallTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnNeverTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnNullableTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromMockObjectRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnCastRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnDirectArrayRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnNewRector;
Expand Down Expand Up @@ -66,6 +67,7 @@ final class TypeDeclarationLevel
AddFunctionVoidReturnTypeWhereNoReturnRector::class,
AddTestsVoidReturnTypeWhereNoReturnRector::class,

ReturnTypeFromMockObjectRector::class,
AddArrowFunctionReturnTypeRector::class,
ReturnTypeFromStrictConstantReturnRector::class,
ReturnTypeFromStrictNewArrayRector::class,
Expand Down

0 comments on commit 48c3f4f

Please sign in to comment.