diff --git a/src/Resolver/NodeExpressionResolver.php b/src/Resolver/NodeExpressionResolver.php index c27b23a..7d2be6c 100644 --- a/src/Resolver/NodeExpressionResolver.php +++ b/src/Resolver/NodeExpressionResolver.php @@ -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(); } /** @@ -517,16 +512,10 @@ 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()); } /** @@ -534,15 +523,11 @@ protected function resolveScalarMagicConstDir(): string */ 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 @@ -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; } } @@ -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|\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. * diff --git a/tests/ConstantsInMemberAttributesTest.php b/tests/ConstantsInMemberAttributesTest.php new file mode 100644 index 0000000..4b021e0 --- /dev/null +++ b/tests/ConstantsInMemberAttributesTest.php @@ -0,0 +1,184 @@ + str_starts_with($className, self::STUB_NAMESPACE . '\\') + ? self::STUB_FILE + : false + )); + } + + protected function tearDown(): void + { + ReflectionEngine::init(new ComposerLocator()); + } + + /** + * @return iterable + */ + 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 + */ + 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 $class + * + * @return array> + */ + 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; + } +} diff --git a/tests/Stub/FileWithConstantsInMemberAttributes.php b/tests/Stub/FileWithConstantsInMemberAttributes.php new file mode 100644 index 0000000..863d0da --- /dev/null +++ b/tests/Stub/FileWithConstantsInMemberAttributes.php @@ -0,0 +1,87 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Go\ParserReflection\Stub\MemberAttributeConstants\Traits { + + use Go\ParserReflection\Stub\MemberAttributeConstants\Flag; + + const LOCAL_FLAG = 'trait-namespace'; + + trait FlaggedTrait + { + #[Flag(LOCAL_FLAG)] + public function fromTrait(): void {} + + #[Flag(__NAMESPACE__)] + public function namespaceFromTrait(): void {} + } +} + +namespace Go\ParserReflection\Stub\MemberAttributeConstants { + + use Go\ParserReflection\Stub\MemberAttributeConstants\Traits\FlaggedTrait; + + const LOCAL_FLAG = 'class-namespace'; + + #[\Attribute(\Attribute::TARGET_ALL | \Attribute::IS_REPEATABLE)] + final class Flag + { + public function __construct(public mixed $value = null) {} + } + + #[Flag(true)] + final class Subject + { + use FlaggedTrait; + + #[Flag(LOCAL_FLAG)] + public const FLAGGED_CONSTANT = 1; + + #[Flag(PHP_INT_MAX)] + public int $flaggedProperty = 0; + + #[Flag(true)] + public function withTrue(): void {} + + #[Flag(false)] + public function withFalse(): void {} + + #[Flag(null)] + public function withNull(): void {} + + #[Flag(TRUE)] + public function withUppercaseTrue(): void {} + + #[Flag(PHP_INT_MAX)] + public function withGlobalConstant(): void {} + + #[Flag(\true)] + public function withQualifiedTrue(): void {} + + #[Flag(self::class)] + public function withClassConstant(): void {} + + #[Flag(LOCAL_FLAG)] + public function withNamespacedConstant(): void {} + + #[Flag(__NAMESPACE__)] + public function withNamespaceMagicConstant(): void {} + + #[Flag([LOCAL_FLAG, PHP_INT_MAX, null])] + public function withConstantsInArray(): void {} + + public function withFlaggedParameter(#[Flag(LOCAL_FLAG)] int $value = PHP_INT_MAX): void {} + } + + #[Flag(LOCAL_FLAG)] + function flaggedFunction(#[Flag(null)] int $value = 0): void {} +}