From a0ed2d304e0344df34b49e010d5f491f0d321d3a Mon Sep 17 00:00:00 2001 From: Ondrej Mirtes Date: Sat, 15 Jan 2022 14:20:33 +0100 Subject: [PATCH] ClassReflection - getBackedEnumType() method --- src/Reflection/ClassReflection.php | 19 +++++++++++++++++++ .../Reflection/ClassReflectionTest.php | 12 ++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/Reflection/ClassReflection.php b/src/Reflection/ClassReflection.php index 90f9dba904..10e4c9aa7a 100644 --- a/src/Reflection/ClassReflection.php +++ b/src/Reflection/ClassReflection.php @@ -29,6 +29,7 @@ use PHPStan\Type\Generic\TemplateTypeScope; use PHPStan\Type\Type; use PHPStan\Type\TypeAlias; +use PHPStan\Type\TypehintHelper; use PHPStan\Type\VerbosityLevel; use ReflectionClass; use ReflectionEnum; @@ -512,6 +513,24 @@ public function isBackedEnum(): bool return $this->reflection->isBacked(); } + public function getBackedEnumType(): ?Type + { + if (!$this->reflection instanceof ReflectionEnum) { + return null; + } + + if (!$this->reflection->isBacked()) { + return null; + } + + $reflectionType = $this->reflection->getBackingType(); + if ($reflectionType === null) { + return null; + } + + return TypehintHelper::decideTypeFromReflection($reflectionType); + } + public function hasEnumCase(string $name): bool { if (!$this->isEnum()) { diff --git a/tests/PHPStan/Reflection/ClassReflectionTest.php b/tests/PHPStan/Reflection/ClassReflectionTest.php index 7e116809f9..2b7eaf367b 100644 --- a/tests/PHPStan/Reflection/ClassReflectionTest.php +++ b/tests/PHPStan/Reflection/ClassReflectionTest.php @@ -33,6 +33,7 @@ use PHPStan\PhpDoc\StubPhpDocProvider; use PHPStan\Testing\PHPStanTestCase; use PHPStan\Type\FileTypeMapper; +use PHPStan\Type\IntegerType; use ReflectionClass; use ReflectionEnum; use WrongClassConstantFile\SecuredRouter; @@ -339,4 +340,15 @@ public function testEnumIsFinal(): void $this->assertTrue($enum->isFinalByKeyword()); } + public function testBackedEnumType(): void + { + if (PHP_VERSION_ID < 80100) { + $this->markTestSkipped('Test requires PHP 8.1.'); + } + + $reflectionProvider = $this->createReflectionProvider(); + $enum = $reflectionProvider->getClass('PHPStan\Fixture\TestEnum'); + $this->assertInstanceOf(IntegerType::class, $enum->getBackedEnumType()); + } + }