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
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
119 changes: 87 additions & 32 deletions src/ReflectionParameter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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;

Expand All @@ -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();
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
Expand All @@ -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;
}
Expand All @@ -326,6 +315,8 @@ public function getDefaultValueConstantName(): null|string
*/
public function getDefaultValueExpression(): ?string
{
$this->resolveDefaultValue();

return $this->defaultValueConstExpr;
}

Expand Down Expand Up @@ -398,6 +389,11 @@ public function isDefaultValueAvailable(): bool
*/
public function isDefaultValueConstant(): bool
{
if (!$this->isDefaultValueAvailable() || !$this->isDefaultValueConstantFetch()) {
return false;
}
$this->resolveDefaultValue();

return $this->isDefaultValueConstant;
}

Expand Down Expand Up @@ -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)
*/
Expand Down
44 changes: 10 additions & 34 deletions src/Resolver/NodeExpressionResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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
Expand Down
36 changes: 28 additions & 8 deletions tests/ConstantExpressionClosuresTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -194,44 +194,64 @@ 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),
'Dependency class should not be loaded before the test'
);

$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);
$reflectionNamespace = $reflectionFile->getFileNamespace(self::STUB_NAMESPACE);
$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('<?php new \\Go\\ParserReflection\\Stub\\ThisClassDoesNotExist();');
$expressionSolver = new NodeExpressionResolver(null);
Expand Down
Loading