From 82a2ba7e080c34d4e8ef81896f36236497bf0fbd Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 22:04:39 +0000 Subject: [PATCH] fix: resolve parameter defaults lazily and load classes through the autoloader Constructing a ReflectionParameter whose default is a `new` expression evaluated the default eagerly, and NodeExpressionResolver loaded the class with include_once of the located file. Reflecting a signature thus declared a class, bypassing the autoloader: in goaop/framework such a class could not be woven any more in that process. - ReflectionParameter resolves its default value on the first access (getDefaultValue(), getDefaultValueConstantName(), isDefaultValueConstant(), getDefaultValueExpression(), __toString()). The implicit nullability of the type is decided on the AST (a literal `null` default), like PHP does at compile time, and only constant fetches are evaluated to answer isDefaultValueConstant(). - NodeExpressionResolver::loadClassDefinition() loads the class through the autoloaders instead of including its file. Fixes #261 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FxhC1GTbduntXjyF8E9Feb --- CLAUDE.md | 2 +- src/ReflectionParameter.php | 119 +++++++++++++++++------ src/Resolver/NodeExpressionResolver.php | 44 ++------- tests/ConstantExpressionClosuresTest.php | 36 +++++-- 4 files changed, 126 insertions(+), 75 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index fdd2b23..7d46248 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,7 +59,7 @@ When you call `new ReflectionClass('SomeClass')`: - `InitializationTrait` — lazy initialization of AST node from engine - `InternalPropertiesEmulationTrait` — makes `var_dump`/serialization look like native reflection - `AttributeResolverTrait` — resolves PHP 8 attributes from AST nodes -- **Resolvers** (`src/Resolver/`) — `NodeExpressionResolver` evaluates constant expressions in the AST (used for default values, constants). `TypeExpressionResolver` resolves type AST nodes into reflection type objects. +- **Resolvers** (`src/Resolver/`) — `NodeExpressionResolver` evaluates constant expressions in the AST (used for default values, constants). `TypeExpressionResolver` resolves type AST nodes into reflection type objects. Expressions that need a real class (`new Foo`, `Foo::bar(...)`) load it through the autoloader (`class_exists()`), never by including its file: library code must not `include`/`require` source files, a class loader hooked into Composer has to see every load. `ReflectionParameter` evaluates its default value lazily (on `getDefaultValue()` and friends), so reflecting a signature has no side effects. - **Missing ancestors** — every parent class, interface and trait is reflected through `ReflectionClass::reflectAncestor()`. When the locator can't find one, `ReflectionEngine::locateClassFile()` throws `ClassNotFoundException`; with `MissingAncestorPolicy::Strict` (default) it propagates, with `MissingAncestorPolicy::Partial` (set via `ReflectionEngine::init()` or `setMissingAncestorPolicy()`) the ancestor is left out. `isPartial()` / `getMissingClassNames()` report missing ancestors (transitively) and never throw. Names stay known from the source: `getParentClassName()` reads the declared parent, `getInterfaceNames()` / `implementsInterface()` / `getTraitNames()` include missing interfaces and traits of a partial class (all read through the private `getAncestorNamesFromSource()`). - **`ReflectionFile` / `ReflectionFileNamespace`** — library-specific (not in native PHP reflection). Allow reflecting arbitrary PHP files and iterating their namespaces, classes, functions without knowing class names in advance. diff --git a/src/ReflectionParameter.php b/src/ReflectionParameter.php index 51e8b95..788ad99 100644 --- a/src/ReflectionParameter.php +++ b/src/ReflectionParameter.php @@ -47,10 +47,18 @@ final class ReflectionParameter extends BaseReflectionParameter implements NodeA */ private ReflectionFunctionAbstract $declaringFunction; + /** + * Whether the default value has been resolved already + * + * The default value is resolved lazily, because its evaluation may have side effects, e.g. a `new` + * expression instantiates (and thus loads) a class, which nobody may need for reflecting a signature. + */ + private bool $isDefaultValueResolved = false; + /** * Stores the default value for node (if present) */ - private mixed $defaultValue; + private mixed $defaultValue = null; /** * Whether or not default value is constant @@ -62,7 +70,7 @@ final class ReflectionParameter extends BaseReflectionParameter implements NodeA * * @see $isDefaultValueConstant */ - private ?string $defaultValueConstantName; + private ?string $defaultValueConstantName = null; /** * Index of parameter in the list @@ -74,9 +82,9 @@ final class ReflectionParameter extends BaseReflectionParameter implements NodeA */ private Param $parameterNode; - private bool $isDefaultValueConstExpr; + private bool $isDefaultValueConstExpr = false; - private ?string $defaultValueConstExpr; + private ?string $defaultValueConstExpr = null; private \ReflectionUnionType|\ReflectionNamedType|\ReflectionIntersectionType|null $type = null; @@ -95,35 +103,10 @@ public function __construct( $this->parameterIndex = $parameterIndex; $this->declaringFunction = $declaringFunction; - if ($declaringFunction instanceof \ReflectionMethod) { - $context = $declaringFunction->getDeclaringClass(); - } elseif ($declaringFunction instanceof \ReflectionFunction) { - $context = $declaringFunction; - } else { - $context = null; - } - - if ($this->isDefaultValueAvailable() && $this->parameterNode->default !== null) { - $expressionSolver = new NodeExpressionResolver($context); - try { - $expressionSolver->process($this->parameterNode->default); - $this->defaultValue = $expressionSolver->getValue(); - $this->isDefaultValueConstant = $expressionSolver->isConstant(); - $this->defaultValueConstantName = $expressionSolver->getConstantName(); - } catch (ReflectionException $e) { - // For first-class callables and other const-expressible values that can't be evaluated - // at parse time, fall back to storing the string expression for code reconstruction. - if (!$expressionSolver->isConstExpression()) { - throw $e; - } - } - $this->isDefaultValueConstExpr = $expressionSolver->isConstExpression(); - $this->defaultValueConstExpr = $expressionSolver->getConstExpression(); - } - if ($this->hasType() && $this->parameterNode->type !== null) { - // If we have null value, this handled internally as nullable type too - $hasDefaultNull = $this->isDefaultValueAvailable() && $this->getDefaultValue() === null; + // A literal null default makes the type implicitly nullable. It is checked on the AST, like PHP does + // at compile time, so that the default value itself does not have to be evaluated here. + $hasDefaultNull = $this->isDefaultValueAvailable() && $this->isDefaultValueNullLiteral(); $declaringClass = $declaringFunction instanceof \ReflectionMethod ? $declaringFunction->getDeclaringClass() : null; $selfClassName = $declaringClass?->getName(); @@ -175,6 +158,7 @@ public function __toString(): string $hasDefaultValue = $this->isDefaultValueAvailable(); $defaultValue = ''; if ($hasDefaultValue) { + $this->resolveDefaultValue(); // For constant fetch expressions, PHP renders now expression if ($this->isDefaultValueConstExpr) { $defaultValue = $this->defaultValueConstExpr; @@ -299,6 +283,7 @@ public function getDefaultValue(): mixed if (!$this->isDefaultValueAvailable()) { throw new ReflectionException('Internal error: Failed to retrieve the default value'); } + $this->resolveDefaultValue(); return $this->defaultValue; } @@ -311,6 +296,10 @@ public function getDefaultValueConstantName(): null|string if (!$this->isDefaultValueAvailable()) { throw new ReflectionException('Internal error: Failed to retrieve the default value'); } + if (!$this->isDefaultValueConstantFetch()) { + return null; + } + $this->resolveDefaultValue(); return $this->defaultValueConstantName; } @@ -326,6 +315,8 @@ public function getDefaultValueConstantName(): null|string */ public function getDefaultValueExpression(): ?string { + $this->resolveDefaultValue(); + return $this->defaultValueConstExpr; } @@ -398,6 +389,11 @@ public function isDefaultValueAvailable(): bool */ public function isDefaultValueConstant(): bool { + if (!$this->isDefaultValueAvailable() || !$this->isDefaultValueConstantFetch()) { + return false; + } + $this->resolveDefaultValue(); + return $this->isDefaultValueConstant; } @@ -433,6 +429,65 @@ public function isVariadic(): bool return $this->parameterNode->variadic; } + /** + * Evaluates the default value expression once, on the first access to the default value + * + * @throws ReflectionException If the default value can not be resolved and has no expression to fall back to + */ + private function resolveDefaultValue(): void + { + if ($this->isDefaultValueResolved || !$this->isDefaultValueAvailable() || $this->parameterNode->default === null) { + return; + } + + $declaringFunction = $this->declaringFunction; + if ($declaringFunction instanceof \ReflectionMethod) { + $context = $declaringFunction->getDeclaringClass(); + } elseif ($declaringFunction instanceof \ReflectionFunction) { + $context = $declaringFunction; + } else { + $context = null; + } + + $expressionSolver = new NodeExpressionResolver($context); + try { + $expressionSolver->process($this->parameterNode->default); + $this->defaultValue = $expressionSolver->getValue(); + $this->isDefaultValueConstant = $expressionSolver->isConstant(); + $this->defaultValueConstantName = $expressionSolver->getConstantName(); + } catch (ReflectionException $e) { + // For first-class callables and other const-expressible values that can't be evaluated + // at parse time, fall back to storing the string expression for code reconstruction. + // Otherwise the error is reported on every access, as the value stays unresolved. + if (!$expressionSolver->isConstExpression()) { + throw $e; + } + } + $this->isDefaultValueConstExpr = $expressionSolver->isConstExpression(); + $this->defaultValueConstExpr = $expressionSolver->getConstExpression(); + $this->isDefaultValueResolved = true; + } + + /** + * Only a constant (`FOO`) or a class constant (`Foo::BAR`) fetch can make the default value a constant + */ + private function isDefaultValueConstantFetch(): bool + { + $default = $this->parameterNode->default; + + return $default instanceof ConstFetch || $default instanceof ClassConstFetch; + } + + /** + * Checks whether the default value is the `null` literal, without evaluating it + */ + private function isDefaultValueNullLiteral(): bool + { + $default = $this->parameterNode->default; + + return $default instanceof ConstFetch && strtolower($default->name->toString()) === 'null'; + } + /** * Returns true if all following parameters are optional (either have values or variadic) */ diff --git a/src/Resolver/NodeExpressionResolver.php b/src/Resolver/NodeExpressionResolver.php index 7d2be6c..811f949 100644 --- a/src/Resolver/NodeExpressionResolver.php +++ b/src/Resolver/NodeExpressionResolver.php @@ -13,7 +13,6 @@ namespace Go\ParserReflection\Resolver; use Go\ParserReflection\ReflectionClass; -use Go\ParserReflection\ReflectionEngine; use Go\ParserReflection\ReflectionException; use Go\ParserReflection\ReflectionFileNamespace; use PhpParser\Node; @@ -325,7 +324,6 @@ protected function resolveExprStaticCall(Expr\StaticCall $node): Closure // Set isConstExpr so callers can reconstruct the expression as code even if resolution fails $this->isConstExpr = true; - // is_callable() and Closure::fromCallable() would silently autoload the class, so it is loaded explicitly $this->loadClassDefinition($className); $callable = $className . '::' . $methodName; @@ -403,7 +401,7 @@ protected function resolveExprNew(Expr\New_ $node): object // Use ReflectionClass to safely instantiate the class $this->loadClassDefinition($className); - if (!class_exists($className, false)) { + if (!class_exists($className)) { throw new ReflectionException("Class '{$className}' does not exist and cannot be instantiated."); } $reflectionClass = new \ReflectionClass($className); @@ -980,43 +978,21 @@ public function enterNode(Node $node): ?Node * Makes the definition of the given class available in the current runtime * * Reflection is performed on the AST only, but several expressions, such as object instantiation or - * first-class callables, can not be represented without a real class definition. For these cases the file - * with the class is resolved via the registered locator and included explicitly, thus an implicit - * autoloading is never triggered by the resolver itself. + * first-class callables, can not be represented without a real class definition. For these cases the class + * is loaded through the registered autoloaders, never by including its file directly: an autoloader (e.g. + * a class loader hooked into Composer) has to see every class load. * - * @throws ReflectionException If the class is not loaded and its file can not be located + * @throws ReflectionException If the class can not be loaded by the autoloaders */ private function loadClassDefinition(string $className): void { - if ($this->isClassDefinitionLoaded($className)) { - return; - } + $isLoaded = class_exists($className) + || interface_exists($className) + || trait_exists($className); - try { - $classFileName = ReflectionEngine::locateClassFile($className); - } catch (\Throwable $e) { - throw new ReflectionException( - "Class '{$className}' is not loaded and its file can not be found by the registered locator.", - 0, - $e - ); + if (!$isLoaded) { + throw new ReflectionException("Class '{$className}' does not exist and can not be loaded by the autoloader."); } - - include_once $classFileName; - - if (!$this->isClassDefinitionLoaded($className)) { - throw new ReflectionException("Class '{$className}' was not found in the file '{$classFileName}'."); - } - } - - /** - * @phpstan-impure The result changes once the located class file has been included - */ - private function isClassDefinitionLoaded(string $className): bool - { - return class_exists($className, false) - || interface_exists($className, false) - || trait_exists($className, false); } private function getDispatchMethodFor(Node $node): string diff --git a/tests/ConstantExpressionClosuresTest.php b/tests/ConstantExpressionClosuresTest.php index 902403d..e09a38c 100644 --- a/tests/ConstantExpressionClosuresTest.php +++ b/tests/ConstantExpressionClosuresTest.php @@ -194,7 +194,14 @@ public function testFirstClassCallableForUnknownFunctionThrowsDescriptiveExcepti } } - public function testNewInInitializerDoesNotTriggerAutoloading(): void + /** + * Reflecting a signature must not load anything, the class of a `new` default is loaded only when the + * default value is requested, and then through the autoloader, so that a class loader hooked into it + * (e.g. goaop/framework) sees the load. + * + * @see https://github.com/goaop/parser-reflection/issues/261 + */ + public function testNewInInitializerIsResolvedLazilyThroughAutoloader(): void { $this->assertFalse( class_exists(self::INITIALIZERS_DEPENDENCY_CLASS, false), @@ -202,10 +209,15 @@ class_exists(self::INITIALIZERS_DEPENDENCY_CLASS, false), ); $autoloadedClasses = []; - $autoloadSpy = static function (string $className) use (&$autoloadedClasses): void { + $stubFileName = $this->initializersFileName; + // Stands in for Composer, which does not know the stub files + $stubAutoloader = static function (string $className) use (&$autoloadedClasses, $stubFileName): void { $autoloadedClasses[] = $className; + if ($className === self::INITIALIZERS_DEPENDENCY_CLASS) { + require_once $stubFileName; + } }; - spl_autoload_register($autoloadSpy); + spl_autoload_register($stubAutoloader); try { $reflectionFile = new ReflectionFile($this->initializersFileName); @@ -213,25 +225,33 @@ class_exists(self::INITIALIZERS_DEPENDENCY_CLASS, false), $parsedMethod = $reflectionNamespace->getClass(self::INITIALIZERS_STUB_CLASS) ->getMethod('withDependency'); - $defaultValue = $parsedMethod->getParameters()[0]->getDefaultValue(); + $parameter = $parsedMethod->getParameters()[0]; + $this->assertTrue($parameter->isDefaultValueAvailable()); + $this->assertFalse($parameter->isDefaultValueConstant()); + $this->assertNotNull($parameter->getType()); + $this->assertFalse($parameter->getType()->allowsNull()); + $this->assertSame([], $autoloadedClasses, 'Reflecting the parameter must not load any class'); + $this->assertFalse(class_exists(self::INITIALIZERS_DEPENDENCY_CLASS, false)); + + $defaultValue = $parameter->getDefaultValue(); } finally { - spl_autoload_unregister($autoloadSpy); + spl_autoload_unregister($stubAutoloader); } $this->assertIsObject($defaultValue); $this->assertSame(self::INITIALIZERS_DEPENDENCY_CLASS, $defaultValue::class); $this->assertSame('injected', $defaultValue->label); - $this->assertNotContains( + $this->assertContains( self::INITIALIZERS_DEPENDENCY_CLASS, $autoloadedClasses, - 'Instantiation of a class in the initializer should not trigger the autoloader' + 'Instantiation of a class in the initializer must load it through the autoloader' ); } public function testNewExpressionForUnknownClassThrowsDescriptiveException(): void { $this->expectException(ReflectionException::class); - $this->expectExceptionMessageMatches('/can not be found by the registered locator/'); + $this->expectExceptionMessageMatches('/can not be loaded by the autoloader/'); $nodes = $this->parser->parse('