Skip to content

Commit

Permalink
Fixed self:: class constant reference in anonymous class
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Feb 25, 2022
1 parent bf36244 commit 96b1e4d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/NodeCompiler/CompileNodeToValue.php
Expand Up @@ -202,7 +202,8 @@ private function getClassConstantValue(Node\Expr\ClassConstFetch $node, ?string
return $className;
}

$classReflection = $context->getReflector()->reflectClass($className);
$classContext = $context->getClass();
$classReflection = $classContext?->getName() === $className ? $classContext : $context->getReflector()->reflectClass($className);

$reflectionConstant = $classReflection->getReflectionConstant($constantName);
if ($classReflection instanceof ReflectionEnum) {
Expand Down
36 changes: 36 additions & 0 deletions test/unit/Reflection/ReflectionClassTest.php
Expand Up @@ -12,6 +12,7 @@
use OutOfBoundsException;
use Php4StyleCaseInsensitiveConstruct;
use Php4StyleConstruct;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Stmt\Class_;
use PHPUnit\Framework\TestCase;
use Qux;
Expand Down Expand Up @@ -2517,4 +2518,39 @@ class FooBar extends Bar
$fooBarDoFooMethod = $fooBar->getMethod('doFoo');
self::assertTrue($fooBarDoFooMethod->isPublic());
}

public function testEvaluateClassConstantFromAnonymousClass(): void
{
$php = <<<'PHP'
<?php
class ApiCacheMap
{
protected const DEFAULT_CACHE_TTL = 600;
protected const CACHE_MAP = [self::DEFAULT_CACHE_TTL => []];
}
PHP;

$source = <<<'PHP'
<?php
new class extends ApiCacheMap {
protected const CACHE_MAP = [
1 => ApiCacheMap::CACHE_MAP[self::DEFAULT_CACHE_TTL],
];
};
PHP;
$parser = BetterReflectionSingleton::instance()->phpParser();
$ast = $parser->parse($source);
$new = $ast[0]->expr;
self::assertInstanceOf(New_::class, $new);

$reflector = (new DefaultReflector(new StringSourceLocator($php, $this->astLocator)));
$anonymous = ReflectionClass::createFromNode(
$reflector,
$new->class,
new LocatedSource($source, null),
);
$array = $anonymous->getConstant('CACHE_MAP');
self::assertIsArray($array);
}
}

0 comments on commit 96b1e4d

Please sign in to comment.