From 0d4a5f82295549ce4ac262a08d39cac186f6b3ea Mon Sep 17 00:00:00 2001 From: Tomas Votruba Date: Sat, 6 Aug 2022 13:37:41 +0200 Subject: [PATCH] [typed] add mock object property type --- .../TypeMapper/IntersectionTypeMapper.php | 20 ++++++++++- .../Fixture/mock_property_type.php.inc | 35 +++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 rules-tests/TypeDeclaration/Rector/Property/TypedPropertyFromAssignsRector/Fixture/mock_property_type.php.inc diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/IntersectionTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/IntersectionTypeMapper.php index 96cbf9c5620..e696aa06172 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/IntersectionTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/IntersectionTypeMapper.php @@ -6,9 +6,11 @@ use PhpParser\Node; use PhpParser\Node\Name; +use PhpParser\Node\Name\FullyQualified; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\Type\Generic\GenericClassStringType; use PHPStan\Type\IntersectionType; +use PHPStan\Type\ObjectType; use PHPStan\Type\Type; use Rector\BetterPhpDocParser\ValueObject\Type\BracketsAwareIntersectionTypeNode; use Rector\Core\Exception\ShouldNotHappenException; @@ -78,7 +80,7 @@ public function mapToPHPStanPhpDocTypeNode(Type $type, string $typeKind): TypeNo public function mapToPhpParserNode(Type $type, string $typeKind): ?Node { if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::INTERSECTION_TYPES)) { - return null; + return $this->matchMockObjectType($type); } $intersectionedTypeNodes = []; @@ -102,4 +104,20 @@ public function mapToPhpParserNode(Type $type, string $typeKind): ?Node return new Node\IntersectionType($intersectionedTypeNodes); } + + private function matchMockObjectType(IntersectionType $intersectionType): ?FullyQualified + { + // return mock object as the strict one + foreach ($intersectionType->getTypes() as $intersectionedType) { + if (! $intersectionedType instanceof ObjectType) { + continue; + } + + if ($intersectionedType->getClassName() === 'PHPUnit\Framework\MockObject\MockObject') { + return new FullyQualified($intersectionedType->getClassName()); + } + } + + return null; + } } diff --git a/rules-tests/TypeDeclaration/Rector/Property/TypedPropertyFromAssignsRector/Fixture/mock_property_type.php.inc b/rules-tests/TypeDeclaration/Rector/Property/TypedPropertyFromAssignsRector/Fixture/mock_property_type.php.inc new file mode 100644 index 00000000000..8e3067d1a01 --- /dev/null +++ b/rules-tests/TypeDeclaration/Rector/Property/TypedPropertyFromAssignsRector/Fixture/mock_property_type.php.inc @@ -0,0 +1,35 @@ +someValue = $this->createMock('SomeClass'); + } +} + +?> +----- +someValue = $this->createMock('SomeClass'); + } +} + +?>