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
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ When you call `new ReflectionClass('SomeClass')`:
- `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.
- **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.
- **`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.

### Test structure
Expand Down
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,46 @@ If project uses a custom autoloader then you should follow the next steps:
1. Create a new class that implements `\Go\ParserReflection\LocatorInterface`
2. Create an instance of that class and pass it to the `ReflectionEngine::init()` method for initial configuration

### Classes whose ancestors can not be located

To reflect a class, the engine has to locate its parent class, interfaces and traits. An ancestor may be impossible
to locate: generated at runtime and loaded by another autoloader, declared by `class_alias()`, or defined outside the
files known to the locator. By default (the *strict* policy) every method that needs such an ancestor throws a
`Go\ParserReflection\ClassNotFoundException`.

With the *partial* policy the missing ancestors are left out instead, and the reflection says that it is partial:

```php
use Go\ParserReflection\MissingAncestorPolicy;
use Go\ParserReflection\ReflectionEngine;

ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Partial);
// or ReflectionEngine::init($locator, null, MissingAncestorPolicy::Partial);

$class = new \Go\ParserReflection\ReflectionClass(SomeClass::class);
if ($class->isPartial()) {
// Names of the parent class, interfaces and traits that can not be located,
// including the ones missing for the available ancestors
var_dump($class->getMissingClassNames());
}
// Own methods, properties, constants and attributes, and the members of the available ancestors
var_dump($class->getMethods());
```

What a partial reflection reports:

- everything declared by the class itself and by its available ancestors stays available;
- a missing parent class is reported by `getParentClass()` as `false`, missing interfaces and traits are left out of
`getInterfaces()`, `getInterfaceNames()`, `getTraits()` and `getTraitNames()`, and the members inherited from
them are left out of `getMethods()`, `getProperties()`, `getConstants()` and alike; a method whose prototype
belongs to a missing ancestor reports no prototype;
- `isSubclassOf()` still recognizes ancestors declared by the class itself, as they are known from its source;
- the names of the ancestors as written stay available from the AST node, see `getNode()`.

`isPartial()` and `getMissingClassNames()` never throw for a missing ancestor, whatever the policy, so they can also
be used to check a class before reflecting it with the strict policy. The class itself must still be located by the
locator: `new ReflectionClass()` for a missing class throws with any policy.

### Reflecting concrete classes/methods/properties without loading them

Just use `Go\ParserReflection` package reflection classes like traditional ones:
Expand Down
13 changes: 12 additions & 1 deletion docs/reflection_class.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,16 @@ List of methods, that require class to be loaded
- ReflectionClass::newInstanceArgs — Creates a new class instance from given arguments.
- ReflectionClass::newInstanceWithoutConstructor — Creates a new class instance without invoking the constructor.
- ReflectionClass::setStaticPropertyValue — Sets static property value


Methods, that are specific for this library
---------

- ReflectionClass::getNode — Returns the AST node of the class.
- ReflectionClass::isPartial — Checks whether some ancestors (parent class, interfaces or traits) of the class can not be located.
- ReflectionClass::getMissingClassNames — Returns the names of the ancestors that can not be located, including the ones missing for the available ancestors.

By default, reflecting an information that needs an ancestor that can not be located throws a
`Go\ParserReflection\ClassNotFoundException`. With `ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Partial)`
the missing ancestors are left out of the reflection instead, see the [README](../README.md) for the details.

[0]: http://php.net/manual/en/class.reflectionclass.php
26 changes: 26 additions & 0 deletions src/ClassNotFoundException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);
/**
* Parser Reflection API
*
* @copyright Copyright 2026, Lisachenko Alexander <lisachenko.it@gmail.com>
*
* This source file is subject to the license that is bundled
* with this source code in the file LICENSE.
*/

namespace Go\ParserReflection;

use InvalidArgumentException;

/**
* Thrown when the registered locator can not find the file of a class
*/
class ClassNotFoundException extends InvalidArgumentException
{
public function __construct(public readonly string $className)
{
parent::__construct("Class $className was not found by locator");
}
}
40 changes: 40 additions & 0 deletions src/MissingAncestorPolicy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);
/**
* Parser Reflection API
*
* @copyright Copyright 2026, Lisachenko Alexander <lisachenko.it@gmail.com>
*
* This source file is subject to the license that is bundled
* with this source code in the file LICENSE.
*/

namespace Go\ParserReflection;

/**
* Tells what the reflection of a class does when an ancestor (parent class, interface or trait) can not be located
*
* An ancestor may be missing when it is generated at runtime and loaded by another autoloader, declared by
* class_alias(), or defined outside the files known to the locator.
*
* @see ReflectionEngine::init()
* @see ReflectionEngine::setMissingAncestorPolicy()
*/
enum MissingAncestorPolicy
{
/**
* Every method that needs a missing ancestor throws a {@see ClassNotFoundException}
*
* This is the default policy.
*/
case Strict;

/**
* Missing ancestors are left out: the reflection covers what the class and its available ancestors declare
*
* Such a reflection reports itself as partial, see {@see ReflectionClass::isPartial()} and
* {@see ReflectionClass::getMissingClassNames()}.
*/
case Partial;
}
180 changes: 138 additions & 42 deletions src/ReflectionClass.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,30 +70,20 @@ public function __construct(object|string $argument, ?ClassLike $classLikeNode =
/**
* Parses interfaces from the concrete class node
*
* An interface that can not be located is left out with the partial {@see MissingAncestorPolicy}.
*
* @return array<string, \ReflectionClass<object>> List of reflections of interfaces
*
* @throws ClassNotFoundException If an interface can not be located with the strict policy
*/
public static function collectInterfacesFromClassNode(ClassLike $classLikeNode): array
{
$interfaces = [];

if ($classLikeNode instanceof Interface_) {
$implementsList = $classLikeNode->extends;
} elseif ($classLikeNode instanceof Class_ || $classLikeNode instanceof Enum_) {
$implementsList = $classLikeNode->implements;
} else {
$implementsList = [];
}

if (count($implementsList) > 0) {
foreach ($implementsList as $implementNode) {
if ($implementNode->getAttribute('resolvedName') instanceof FullyQualified) {
$implementName = $implementNode->getAttribute('resolvedName')->toString();
$interface = interface_exists($implementName, false)
? new parent($implementName)
: new self($implementName);

$interfaces[$implementName] = $interface;
}
foreach (self::getDeclaredInterfaceNames($classLikeNode) as $interfaceName) {
$interface = self::reflectAncestor($interfaceName);
if ($interface !== null) {
$interfaces[$interfaceName] = $interface;
}
}

Expand All @@ -114,34 +104,152 @@ public static function collectInterfacesFromClassNode(ClassLike $classLikeNode):
/**
* Parses traits from the concrete class node
*
* A trait that can not be located is left out with the partial {@see MissingAncestorPolicy}.
*
* @param array<int|string, \PhpParser\Node\Stmt\TraitUseAdaptation> $traitAdaptations List of method adaptations
*
* @return \ReflectionClass<object>[] List of reflections of traits
*
* @throws ClassNotFoundException If a trait can not be located with the strict policy
*/
public static function collectTraitsFromClassNode(ClassLike $classLikeNode, array &$traitAdaptations): array
{
$traits = [];

if (!empty($classLikeNode->stmts)) {
foreach ($classLikeNode->stmts as $classLevelNode) {
if ($classLevelNode instanceof TraitUse) {
foreach ($classLevelNode->traits as $classTraitName) {
if ($classTraitName->getAttribute('resolvedName') instanceof FullyQualified) {
$traitName = $classTraitName->getAttribute('resolvedName')->toString();
$trait = trait_exists($traitName, false)
? new parent($traitName)
: new self($traitName);
$traits[$traitName] = $trait;
}
foreach ($classLikeNode->stmts as $classLevelNode) {
if ($classLevelNode instanceof TraitUse) {
foreach (self::getResolvedNames($classLevelNode->traits) as $traitName) {
$trait = self::reflectAncestor($traitName);
if ($trait !== null) {
$traits[$traitName] = $trait;
}
$traitAdaptations = array_merge($traitAdaptations, $classLevelNode->adaptations);
}
$traitAdaptations = array_merge($traitAdaptations, $classLevelNode->adaptations);
}
}

return $traits;
}

/**
* Collects the names of the ancestors of the class node that can not be located
*
* The ancestors that can not be located for the available ancestors are included as well. Ancestors are
* checked without throwing, whatever the {@see MissingAncestorPolicy} is.
*
* @return list<string>
*/
public static function collectMissingAncestorNames(ClassLike $classLikeNode): array
{
$ancestorNames = self::getDeclaredInterfaceNames($classLikeNode);
$parentName = self::getDeclaredParentName($classLikeNode);
if ($parentName !== null) {
array_unshift($ancestorNames, $parentName);
}
foreach ($classLikeNode->stmts as $classLevelNode) {
if ($classLevelNode instanceof TraitUse) {
array_push($ancestorNames, ...self::getResolvedNames($classLevelNode->traits));
}
}

$missingNames = [];
foreach ($ancestorNames as $ancestorName) {
$ancestor = self::reflectAncestor($ancestorName, true);
if ($ancestor === null) {
$missingNames[] = $ancestorName;
} elseif ($ancestor instanceof self) {
// A declared ancestor is reflected natively, so it is never partial
array_push($missingNames, ...$ancestor->getMissingClassNames());
}
}

return array_values(array_unique($missingNames));
}

/**
* Reflects an ancestor (parent class, interface or trait) of a parsed class
*
* An ancestor already declared in the runtime is reflected natively, otherwise its source is located and parsed.
*
* @internal
*
* @param bool|null $allowMissing Whether to return null instead of throwing when the ancestor can not be
* located, null to follow the {@see MissingAncestorPolicy} of the engine
*
* @return \ReflectionClass<object>|null Null if the ancestor can not be located and that is allowed
*
* @throws ClassNotFoundException If the ancestor can not be located and that is not allowed
*/
public static function reflectAncestor(string $ancestorName, ?bool $allowMissing = null): ?InternalReflectionClass
{
if (class_exists($ancestorName, false)
|| interface_exists($ancestorName, false)
|| trait_exists($ancestorName, false)
) {
return new parent($ancestorName);
}

try {
return new self($ancestorName);
} catch (ClassNotFoundException $e) {
$allowMissing ??= ReflectionEngine::getMissingAncestorPolicy() === MissingAncestorPolicy::Partial;
if (!$allowMissing) {
throw $e;
}

return null;
}
}

/**
* Returns the resolved name of the parent class declared by the class node, if any
*/
private static function getDeclaredParentName(ClassLike $classLikeNode): ?string
{
if (!$classLikeNode instanceof Class_ || $classLikeNode->extends === null) {
return null;
}

return self::getResolvedNames([$classLikeNode->extends])[0] ?? null;
}

/**
* Returns the resolved names of the interfaces declared by the class node, in declaration order
*
* @return list<string>
*/
private static function getDeclaredInterfaceNames(ClassLike $classLikeNode): array
{
if ($classLikeNode instanceof Interface_) {
return self::getResolvedNames($classLikeNode->extends);
}
if ($classLikeNode instanceof Class_ || $classLikeNode instanceof Enum_) {
return self::getResolvedNames($classLikeNode->implements);
}

return [];
}

/**
* Returns the fully qualified names resolved for the given name nodes
*
* @param Name[] $nameNodes
*
* @return list<string>
*/
private static function getResolvedNames(array $nameNodes): array
{
$resolvedNames = [];
foreach ($nameNodes as $nameNode) {
$resolvedName = $nameNode->getAttribute('resolvedName');
if ($resolvedName instanceof FullyQualified) {
$resolvedNames[] = $resolvedName->toString();
}
}

return $resolvedNames;
}

/**
* Creates a native ReflectionClass instance for the given class/interface name.
*
Expand Down Expand Up @@ -186,16 +294,4 @@ protected function __initialize(): void
{
parent::__construct($this->getName());
}

/**
* Create a ReflectionClass for a given class name.
*
* @param string $className The name of the class to create a reflection for.
*
* @return \ReflectionClass<object> The appropriate reflection object.
*/
protected function createReflectionForClass(string $className): InternalReflectionClass
{
return class_exists($className, false) ? new parent($className) : new self($className);
}
}
Loading
Loading