Skip to content

Commit

Permalink
Merge pull request #1386 from ondrejmirtes/fix-enum
Browse files Browse the repository at this point in the history
CompileNodeToValue - allow getting enum constant
  • Loading branch information
Ocramius authored Jan 4, 2024
2 parents 64af8fa + 59d82ca commit 7f9bf2c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/NodeCompiler/CompileNodeToValue.php
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,9 @@ private function getClassConstantValue(Node\Expr\ClassConstFetch $node, string|n
$classReflection = $classContext !== null && $classContext->getName() === $className ? $classContext : $context->getReflector()->reflectClass($className);

if ($classReflection instanceof ReflectionEnum) {
throw Exception\UnableToCompileNode::becauseOfValueIsEnum($context, $classReflection, $node);
if ($classReflection->hasCase($constantName)) {
throw Exception\UnableToCompileNode::becauseOfValueIsEnum($context, $classReflection, $node);
}
}

$reflectionConstant = $classReflection->getConstant($constantName);
Expand Down
22 changes: 22 additions & 0 deletions test/unit/NodeCompiler/CompileNodeToValueTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -764,6 +764,28 @@ class Bat {
$classInfo->getConstant('ONE_VALUE')->getValue();
}

public function testEnumConstantValueDoesNotThrowException(): void
{
$phpCode = <<<'PHP'
<?php
enum Foo: int {
const ONE = 1;
}
class Bat {
const ONE_VALUE = Foo::ONE;
}
PHP;

$reflector = new DefaultReflector(new AggregateSourceLocator([
new StringSourceLocator($phpCode, $this->astLocator),
new PhpInternalSourceLocator($this->astLocator, $this->sourceStubber),
]));
$classInfo = $reflector->reflectClass('Bat');

self::assertSame(1, $classInfo->getConstant('ONE_VALUE')->getValue());
}

/** @return list<array{0: string, 1: mixed}> */
public static function magicConstantsWithoutNamespaceProvider(): array
{
Expand Down

0 comments on commit 7f9bf2c

Please sign in to comment.