diff --git a/rules-tests/TypeDeclaration/Rector/Class_/TypedPropertyFromCreateMockAssignRector/Fixture/skip_intersection_type.php.inc b/rules-tests/TypeDeclaration/Rector/Class_/TypedPropertyFromCreateMockAssignRector/Fixture/skip_intersection_type.php.inc new file mode 100644 index 0000000000..986a5c7f7f --- /dev/null +++ b/rules-tests/TypeDeclaration/Rector/Class_/TypedPropertyFromCreateMockAssignRector/Fixture/skip_intersection_type.php.inc @@ -0,0 +1,17 @@ +someMock = $this->createMock(SomeMockedClass::class); + } +} diff --git a/rules/TypeDeclaration/Rector/Class_/TypedPropertyFromCreateMockAssignRector.php b/rules/TypeDeclaration/Rector/Class_/TypedPropertyFromCreateMockAssignRector.php index 0256223cd5..61ffbd0164 100644 --- a/rules/TypeDeclaration/Rector/Class_/TypedPropertyFromCreateMockAssignRector.php +++ b/rules/TypeDeclaration/Rector/Class_/TypedPropertyFromCreateMockAssignRector.php @@ -34,7 +34,7 @@ public function __construct( public function getRuleDefinition(): RuleDefinition { - return new RuleDefinition('Add typed property from assigned mock', [ + return new RuleDefinition('Add "PHPUnit\Framework\MockObject\MockObject" typed property from assigned mock to clearly separate from real objects', [ new CodeSample( <<<'CODE_SAMPLE' use PHPUnit\Framework\TestCase; @@ -52,10 +52,11 @@ protected function setUp(): void , <<<'CODE_SAMPLE' use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\MockObject\MockObject; final class SomeTest extends TestCase { - private \PHPUnit\Framework\MockObject\MockObject $someProperty; + private MockObject $someProperty; protected function setUp(): void { @@ -84,15 +85,13 @@ public function refactor(Node $node): ?Node $hasChanged = false; foreach ($node->getProperties() as $property) { - // already use PHPUnit\Framework\MockObject\MockObject type - if ($property->type instanceof Node && $this->isObjectType( - $property->type, - new ObjectType(ClassName::MOCK_OBJECT) - )) { + if (count($property->props) !== 1) { continue; } - if (count($property->props) !== 1) { + + // already use PHPUnit\Framework\MockObject\MockObject type + if ($this->isAlreadyTypedWithMockObject($property)) { continue; } @@ -135,4 +134,18 @@ public function provideMinPhpVersion(): int { return PhpVersionFeature::TYPED_PROPERTIES; } + + private function isAlreadyTypedWithMockObject(Node\Stmt\Property $property): bool + { + if (! $property->type instanceof Node) { + return false; + } + + // complex type, used on purpose + if ($property->type instanceof Node\IntersectionType) { + return true; + } + + return $this->isObjectType($property->type, new ObjectType(ClassName::MOCK_OBJECT)); + } }