Skip to content

Commit

Permalink
ClassReflection - getBackedEnumType() method
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Jan 15, 2022
1 parent 0eb9a63 commit a0ed2d3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Reflection/ClassReflection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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()) {
Expand Down
12 changes: 12 additions & 0 deletions tests/PHPStan/Reflection/ClassReflectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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());
}

}

0 comments on commit a0ed2d3

Please sign in to comment.