Skip to content

Commit

Permalink
Merge pull request #1380 from forrest79/unable-to-get-enum-value
Browse files Browse the repository at this point in the history
Better exception message for when default value is an enum
  • Loading branch information
Ocramius authored Dec 7, 2023
2 parents 7a7c9c3 + 2ae41b8 commit 92e9cbd
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/NodeCompiler/CompileNodeToValue.php
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,10 @@ private function getClassConstantValue(Node\Expr\ClassConstFetch $node, string|n
$classContext = $context->getClass();
$classReflection = $classContext !== null && $classContext->getName() === $className ? $classContext : $context->getReflector()->reflectClass($className);

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

$reflectionConstant = $classReflection->getConstant($constantName);

if (! $reflectionConstant instanceof ReflectionClassConstant) {
Expand Down
17 changes: 17 additions & 0 deletions src/NodeCompiler/Exception/UnableToCompileNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,23 @@ public static function becauseOfInitializer(
));
}

public static function becauseOfValueIsEnum(
CompilerContext $fetchContext,
ReflectionClass $targetClass,
Node\Expr\ClassConstFetch $constantFetch,
): self {
assert($constantFetch->name instanceof Node\Identifier);

return new self(sprintf(
'An enum expression %s::%s is not supported in %s in file %s (line %d)',
$targetClass->getName(),
$constantFetch->name->name,
self::compilerContextToContextDescription($fetchContext),
self::getFileName($fetchContext),
$constantFetch->getLine(),
));
}

private static function getFileName(CompilerContext $fetchContext): string
{
$fileName = $fetchContext->getFileName();
Expand Down
23 changes: 23 additions & 0 deletions test/unit/NodeCompiler/CompileNodeToValueTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -741,6 +741,29 @@ class Bat {
$classInfo->getConstant('ONE_VALUE')->getValue();
}

public function testEnumValueThrowsException(): void
{
$phpCode = <<<'PHP'
<?php
enum Foo: int {
case 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');

$this->expectExceptionMessage('An enum expression Foo::ONE is not supported in class Bat in file ');
$classInfo->getConstant('ONE_VALUE')->getValue();
}

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

0 comments on commit 92e9cbd

Please sign in to comment.