Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 70 additions & 40 deletions src/Resolver/NodeExpressionResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -480,17 +480,12 @@ protected function resolveScalarMagicConstFunction(): string
*/
protected function resolveScalarMagicConstNamespace(): string
{
if ($this->context instanceof ReflectionFileNamespace) {
return $this->context->getName();
}
if (!($this->context instanceof \ReflectionClass
|| $this->context instanceof \ReflectionFunction
|| $this->context instanceof \ReflectionMethod
)) {
$scope = $this->getContextScope();
if ($scope === null) {
throw new ReflectionException("Could not resolve __NAMESPACE__ without having getNamespaceName");
}

return $this->context->getNamespaceName();
return $scope instanceof ReflectionFileNamespace ? $scope->getName() : $scope->getNamespaceName();
}

/**
Expand All @@ -517,32 +512,22 @@ protected function resolveScalarMagicConstClass(): string
*/
protected function resolveScalarMagicConstDir(): string
{
if (!($this->context instanceof \ReflectionClass
|| $this->context instanceof \ReflectionFunction
|| $this->context instanceof \ReflectionMethod
|| $this->context instanceof ReflectionFileNamespace
)) {
if ($this->getContextScope() === null) {
throw new ReflectionException("Could not resolve __DIR__ without having getFileName");
}
$fileName = $this->context->getFileName();

return dirname((string) $fileName);
return dirname($this->getContextFileName());
}

/**
* @throws ReflectionException If ReflectionContext doesn't have getFileName
*/
protected function resolveScalarMagicConstFile(): string
{
if (!($this->context instanceof \ReflectionClass
|| $this->context instanceof \ReflectionFunction
|| $this->context instanceof \ReflectionMethod
|| $this->context instanceof ReflectionFileNamespace
)) {
if ($this->getContextScope() === null) {
throw new ReflectionException("Could not resolve __FILE__ without having getFileName");
}

return (string) $this->context->getFileName();
return $this->getContextFileName();
}

protected function resolveScalarMagicConstLine(Line $node): int
Expand Down Expand Up @@ -578,29 +563,28 @@ protected function resolveExprConstFetch(Expr\ConstFetch $node): mixed
$isFQNConstant = $nodeConstantName instanceof Node\Name\FullyQualified;
$constantName = $nodeConstantName->toString();

if (!$isFQNConstant && ($this->context instanceof \ReflectionClass
|| $this->context instanceof \ReflectionFunction
|| $this->context instanceof \ReflectionMethod
|| $this->context instanceof ReflectionFileNamespace
)) {
$fileName = (string) $this->context->getFileName();
$namespaceName = $this->resolveScalarMagicConstNamespace();
$fileNamespace = new ReflectionFileNamespace($fileName, $namespaceName);
if ($fileNamespace->hasConstant($constantName)) {
$constantValue = $fileNamespace->getConstant($constantName);
$constantName = $fileNamespace->getName() . '\\' . $constantName;
$isResolved = true;
$isRealConstant = !isset(self::$notConstants[strtolower($constantName)]);
$scope = $isFQNConstant ? null : $this->getContextScope();
// true, false and null can not be redefined in a namespace, so there is nothing to look up for them
if ($scope !== null && $isRealConstant) {
$fileName = $this->getContextFileName();
// Code that is not stored in a file (e.g. evaluated or passed as a string) has no namespace to look into
if ($fileName !== '') {
$fileNamespace = $scope instanceof ReflectionFileNamespace
? $scope
: new ReflectionFileNamespace($fileName, $scope->getNamespaceName());
if ($fileNamespace->hasConstant($constantName)) {
$constantValue = $fileNamespace->getConstant($constantName);
$constantName = $fileNamespace->getName() . '\\' . $constantName;
$isResolved = true;
}
}
}

$isRealConstant = !isset(self::$notConstants[$constantName]);
if (!$isResolved && defined($constantName)) {
$constantValue = constant($constantName);
if (!$isFQNConstant && ($this->context instanceof \ReflectionClass
|| $this->context instanceof \ReflectionFunction
|| $this->context instanceof \ReflectionMethod
)) {
$constantName = $this->context->getNamespaceName() . '\\' . $constantName;
if ($scope !== null && !$scope instanceof ReflectionFileNamespace) {
$constantName = $scope->getNamespaceName() . '\\' . $constantName;
}
}

Expand Down Expand Up @@ -1042,6 +1026,52 @@ private function getDispatchMethodFor(Node $node): string
return 'resolve' . str_replace('_', '', $nodeType);
}

/**
* Returns the reflector that owns the file and namespace of the code in the current context.
*
* Class members (methods, properties, constants) and method parameters are declared inside a class,
* so their namespace and file are the ones of the declaring class (or of the trait, for the imported
* members), function parameters belong to their function. The namespace of a class member itself is
* always empty, like in the native reflection, so it can not be used to resolve names.
*
* @return \ReflectionClass<object>|\ReflectionFunction|ReflectionFileNamespace|null
*/
private function getContextScope(): \ReflectionClass|\ReflectionFunction|ReflectionFileNamespace|null
{
$context = $this->context;
if ($context instanceof \ReflectionParameter) {
$context = $context->getDeclaringFunction();
}

return match (true) {
$context instanceof \ReflectionClass,
$context instanceof \ReflectionFunction,
$context instanceof ReflectionFileNamespace => $context,
$context instanceof \ReflectionMethod,
$context instanceof \ReflectionProperty,
$context instanceof \ReflectionClassConstant => $context->getDeclaringClass(),
default => null,
};
}

/**
* Returns the name of the file with the code in the current context, or an empty string if it is unknown.
*
* A method reflected on its own may not know its file name, so the declaring class is asked as well.
*/
private function getContextFileName(): string
{
$context = $this->context instanceof \ReflectionParameter
? $this->context->getDeclaringFunction()
: $this->context;
$fileName = $context instanceof \ReflectionFunctionAbstract ? $context->getFileName() : false;
if ($fileName === false || $fileName === '') {
$fileName = $this->getContextScope()?->getFileName();
}

return is_string($fileName) ? $fileName : '';
}

/**
* Returns the \ReflectionClass for the current context, if available.
*
Expand Down
184 changes: 184 additions & 0 deletions tests/ConstantsInMemberAttributesTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
<?php
declare(strict_types=1);

namespace Go\ParserReflection;

use Go\ParserReflection\Locator\CallableLocator;
use Go\ParserReflection\Locator\ComposerLocator;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

/**
* Unqualified constants (true, false, null, global and namespaced constants) in the attribute arguments
* of class members must be resolved in the namespace of the declaring class
*
* @see https://github.com/goaop/parser-reflection/issues/259
*/
class ConstantsInMemberAttributesTest extends TestCase
{
private const STUB_FILE = __DIR__ . '/Stub/FileWithConstantsInMemberAttributes.php';

private const STUB_NAMESPACE = 'Go\ParserReflection\Stub\MemberAttributeConstants';

private const SUBJECT_CLASS = self::STUB_NAMESPACE . '\Subject';

protected function setUp(): void
{
// The stub is resolved from the AST only, the locator knows nothing but this file
ReflectionEngine::init(new CallableLocator(
fn(string $className): false|string => str_starts_with($className, self::STUB_NAMESPACE . '\\')
? self::STUB_FILE
: false
));
}

protected function tearDown(): void
{
ReflectionEngine::init(new ComposerLocator());
}

/**
* @return iterable<string, array{string, mixed}>
*/
public static function methodAttributeArgumentsProvider(): iterable
{
yield 'true' => ['withTrue', true];
yield 'false' => ['withFalse', false];
yield 'null' => ['withNull', null];
yield 'uppercase TRUE' => ['withUppercaseTrue', true];
yield 'global constant' => ['withGlobalConstant', PHP_INT_MAX];
yield 'qualified true' => ['withQualifiedTrue', true];
yield 'class constant' => ['withClassConstant', self::SUBJECT_CLASS];
yield 'namespaced constant' => ['withNamespacedConstant', 'class-namespace'];
yield '__NAMESPACE__' => ['withNamespaceMagicConstant', self::STUB_NAMESPACE];
yield 'constants in array' => ['withConstantsInArray', ['class-namespace', PHP_INT_MAX, null]];
}

/**
* Methods imported from a trait resolve names in the namespace of the trait, not of the using class
*
* @return iterable<string, array{string, mixed}>
*/
public static function traitMethodAttributeArgumentsProvider(): iterable
{
yield 'trait constant' => ['fromTrait', 'trait-namespace'];
yield 'trait __NAMESPACE__' => ['namespaceFromTrait', self::STUB_NAMESPACE . '\Traits'];
}

#[DataProvider('methodAttributeArgumentsProvider')]
#[DataProvider('traitMethodAttributeArgumentsProvider')]
public function testMethodReflectedThroughClass(string $methodName, mixed $expectedValue): void
{
$method = (new ReflectionClass(self::SUBJECT_CLASS))->getMethod($methodName);

$this->assertSame([$expectedValue], $method->getAttributes()[0]->getArguments());
}

#[DataProvider('methodAttributeArgumentsProvider')]
public function testMethodReflectedOnItsOwn(string $methodName, mixed $expectedValue): void
{
$method = new ReflectionMethod(self::SUBJECT_CLASS, $methodName);

$this->assertSame([$expectedValue], $method->getAttributes()[0]->getArguments());
}

public function testClassAttribute(): void
{
$class = new ReflectionClass(self::SUBJECT_CLASS);

$this->assertSame([true], $class->getAttributes()[0]->getArguments());
}

public function testClassConstantAttribute(): void
{
$constant = (new ReflectionClass(self::SUBJECT_CLASS))->getReflectionConstant('FLAGGED_CONSTANT');
$this->assertInstanceOf(ReflectionClassConstant::class, $constant);

$this->assertSame(['class-namespace'], $constant->getAttributes()[0]->getArguments());
}

public function testPropertyAttribute(): void
{
$property = (new ReflectionClass(self::SUBJECT_CLASS))->getProperty('flaggedProperty');

$this->assertSame([PHP_INT_MAX], $property->getAttributes()[0]->getArguments());
}

public function testMethodParameterAttribute(): void
{
$parameter = (new ReflectionMethod(self::SUBJECT_CLASS, 'withFlaggedParameter'))->getParameters()[0];

$this->assertSame(['class-namespace'], $parameter->getAttributes()[0]->getArguments());
$this->assertSame(PHP_INT_MAX, $parameter->getDefaultValue());
}

public function testFunctionAndFunctionParameterAttributes(): void
{
$function = (new ReflectionFile(self::STUB_FILE))
->getFileNamespace(self::STUB_NAMESPACE)
->getFunction('flaggedFunction');
$this->assertInstanceOf(ReflectionFunction::class, $function);

$this->assertSame(['class-namespace'], $function->getAttributes()[0]->getArguments());
$this->assertSame([null], $function->getParameters()[0]->getAttributes()[0]->getArguments());
}

/**
* The same arguments must be reported by the native reflection once the stub is loaded
*/
public function testParityWithNativeReflection(): void
{
$parsedClass = new ReflectionClass(self::SUBJECT_CLASS);
$parsedFunction = (new ReflectionFile(self::STUB_FILE))
->getFileNamespace(self::STUB_NAMESPACE)
->getFunction('flaggedFunction');
$this->assertInstanceOf(ReflectionFunction::class, $parsedFunction);

// Collect everything before loading, so that the AST is the only source of the parsed values
$parsedArguments = $this->collectAttributeArguments($parsedClass, $parsedFunction);

require_once self::STUB_FILE;
$nativeArguments = $this->collectAttributeArguments(
new \ReflectionClass(self::SUBJECT_CLASS),
new \ReflectionFunction(self::STUB_NAMESPACE . '\flaggedFunction')
);

$this->assertSame($nativeArguments, $parsedArguments);
}

/**
* @param \ReflectionClass<object> $class
*
* @return array<string, list<mixed>>
*/
private function collectAttributeArguments(\ReflectionClass $class, \ReflectionFunction $function): array
{
$arguments = [];
$collect = static function (string $key, \Reflector $reflector) use (&$arguments): void {
foreach ($reflector->getAttributes() as $attribute) {
$arguments[$key][] = $attribute->getArguments();
}
};

$collect('class', $class);
foreach ($class->getMethods() as $method) {
$collect('method ' . $method->getName(), $method);
foreach ($method->getParameters() as $parameter) {
$collect('parameter ' . $method->getName() . '::$' . $parameter->getName(), $parameter);
}
}
foreach ($class->getProperties() as $property) {
$collect('property ' . $property->getName(), $property);
}
foreach ($class->getReflectionConstants() as $constant) {
$collect('constant ' . $constant->getName(), $constant);
}
$collect('function', $function);
foreach ($function->getParameters() as $parameter) {
$collect('function parameter $' . $parameter->getName(), $parameter);
}
ksort($arguments);

return $arguments;
}
}
Loading
Loading