Skip to content

Commit a0ed2d3

Browse files
committed
ClassReflection - getBackedEnumType() method
1 parent 0eb9a63 commit a0ed2d3

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/Reflection/ClassReflection.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
use PHPStan\Type\Generic\TemplateTypeScope;
3030
use PHPStan\Type\Type;
3131
use PHPStan\Type\TypeAlias;
32+
use PHPStan\Type\TypehintHelper;
3233
use PHPStan\Type\VerbosityLevel;
3334
use ReflectionClass;
3435
use ReflectionEnum;
@@ -512,6 +513,24 @@ public function isBackedEnum(): bool
512513
return $this->reflection->isBacked();
513514
}
514515

516+
public function getBackedEnumType(): ?Type
517+
{
518+
if (!$this->reflection instanceof ReflectionEnum) {
519+
return null;
520+
}
521+
522+
if (!$this->reflection->isBacked()) {
523+
return null;
524+
}
525+
526+
$reflectionType = $this->reflection->getBackingType();
527+
if ($reflectionType === null) {
528+
return null;
529+
}
530+
531+
return TypehintHelper::decideTypeFromReflection($reflectionType);
532+
}
533+
515534
public function hasEnumCase(string $name): bool
516535
{
517536
if (!$this->isEnum()) {

tests/PHPStan/Reflection/ClassReflectionTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
use PHPStan\PhpDoc\StubPhpDocProvider;
3434
use PHPStan\Testing\PHPStanTestCase;
3535
use PHPStan\Type\FileTypeMapper;
36+
use PHPStan\Type\IntegerType;
3637
use ReflectionClass;
3738
use ReflectionEnum;
3839
use WrongClassConstantFile\SecuredRouter;
@@ -339,4 +340,15 @@ public function testEnumIsFinal(): void
339340
$this->assertTrue($enum->isFinalByKeyword());
340341
}
341342

343+
public function testBackedEnumType(): void
344+
{
345+
if (PHP_VERSION_ID < 80100) {
346+
$this->markTestSkipped('Test requires PHP 8.1.');
347+
}
348+
349+
$reflectionProvider = $this->createReflectionProvider();
350+
$enum = $reflectionProvider->getClass('PHPStan\Fixture\TestEnum');
351+
$this->assertInstanceOf(IntegerType::class, $enum->getBackedEnumType());
352+
}
353+
342354
}

0 commit comments

Comments
 (0)