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 @@ -60,7 +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.
- **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.

### Test structure
Expand Down
12 changes: 7 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,13 @@ 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()`.
`getInterfaces()` and `getTraits()`, 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;
- the names of the missing ancestors are known from the source: `getParentClassName()` returns the name of the parent
class as written, located or not, `getInterfaceNames()` and `implementsInterface()` include the missing interfaces
declared by the class and by its available ancestors, `getTraitNames()` includes the missing traits the class uses,
and `isSubclassOf()` recognizes the ancestors declared by the class itself.

`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
Expand Down
1 change: 1 addition & 0 deletions docs/reflection_class.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ 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.
- ReflectionClass::getParentClassName — Returns the name of the parent class as written in the source, also when the parent class can not be located.

By default, reflecting an information that needs an ancestor that can not be located throws a
`Go\ParserReflection\ClassNotFoundException`. With `ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Partial)`
Expand Down
71 changes: 6 additions & 65 deletions src/ReflectionClass.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,12 @@ public static function collectInterfacesFromClassNode(ClassLike $classLikeNode):
{
$interfaces = [];

foreach (self::getDeclaredInterfaceNames($classLikeNode) as $interfaceName) {
$interfaceNodes = match (true) {
$classLikeNode instanceof Interface_ => $classLikeNode->extends,
$classLikeNode instanceof Class_, $classLikeNode instanceof Enum_ => $classLikeNode->implements,
default => [],
};
foreach (self::getResolvedNames($interfaceNodes) as $interfaceName) {
$interface = self::reflectAncestor($interfaceName);
if ($interface !== null) {
$interfaces[$interfaceName] = $interface;
Expand Down Expand Up @@ -131,41 +136,6 @@ public static function collectTraitsFromClassNode(ClassLike $classLikeNode, arra
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
*
Expand Down Expand Up @@ -201,35 +171,6 @@ public static function reflectAncestor(string $ancestorName, ?bool $allowMissing
}
}

/**
* 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
*
Expand Down
123 changes: 107 additions & 16 deletions src/Traits/ReflectionClassLikeTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
use PhpParser\Node\Stmt\Enum_;
use PhpParser\Node\Stmt\Interface_;
use PhpParser\Node\Stmt\Trait_;
use PhpParser\Node\Stmt\TraitUse;
use PhpParser\Node\Stmt\TraitUseAdaptation;
use ReflectionExtension;
use ReflectionObject;
Expand Down Expand Up @@ -356,10 +357,28 @@ public function getFileName(): string|false

/**
* {@inheritDoc}
*
* A partial reflection also names the interfaces that can not be located, as written in the source of the class
* and of its available ancestors: they are left out of getInterfaces() only.
*/
public function getInterfaceNames(): array
{
return array_keys($this->getInterfaces());
$interfaceNames = array_keys($this->getInterfaces());
if (!$this->isPartial()) {
return $interfaceNames;
}

$parentClass = $this->getParentClass();
if ($parentClass !== false) {
array_push($interfaceNames, ...$parentClass->getInterfaceNames());
}
foreach (ReflectionClass::collectInterfacesFromClassNode($this->classLikeNode) as $interface) {
array_push($interfaceNames, ...$interface->getInterfaceNames());
}
[, $declaredInterfaceNames] = $this->getAncestorNamesFromSource();
array_push($interfaceNames, ...array_intersect($declaredInterfaceNames, $this->getMissingClassNames()));

return array_values(array_unique($interfaceNames));
}

/**
Expand Down Expand Up @@ -530,7 +549,23 @@ public function getNamespaceName(): string
public function getMissingClassNames(): array
{
if (!isset($this->missingClassNames)) {
$this->missingClassNames = ReflectionClass::collectMissingAncestorNames($this->classLikeNode);
[$parentName, $interfaceNames, $traitNames] = $this->getAncestorNamesFromSource();
$ancestorNames = [...$interfaceNames, ...$traitNames];
if ($parentName !== null) {
array_unshift($ancestorNames, $parentName);
}

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

return $this->missingClassNames;
Expand All @@ -550,6 +585,20 @@ public function isPartial(): bool
return $this->getMissingClassNames() !== [];
}

/**
* Returns the name of the parent class as written in the source of the class, without reflecting the parent
*
* Unlike getParentClass(), it also names a parent class that can not be located (see isPartial()).
*
* @return string|false Fully qualified name of the parent class, false if the class declares none
*/
public function getParentClassName(): string|false
{
[$parentName] = $this->getAncestorNamesFromSource();

return $parentName ?? false;
}

/**
* {@inheritDoc}
*
Expand All @@ -561,15 +610,8 @@ public function isPartial(): bool
public function getParentClass(): \ReflectionClass|false
{
if (!isset($this->parentClass)) {

$parentClass = false;
$extendsNode = $this->classLikeNode->extends ?? null;

if ($extendsNode instanceof Name && $extendsNode->getAttribute('resolvedName') instanceof FullyQualified) {
$extendsName = $extendsNode->getAttribute('resolvedName')->toString();
$parentClass = ReflectionClass::reflectAncestor($extendsName) ?? false;
}
$this->parentClass = $parentClass;
$parentName = $this->getParentClassName();
$this->parentClass = $parentName !== false ? (ReflectionClass::reflectAncestor($parentName) ?? false) : false;
}

return $this->parentClass;
Expand Down Expand Up @@ -736,10 +778,58 @@ public function getTraitAliases(): array
* Returns an array of names of traits used by this class
*
* @link http://php.net/manual/en/reflectionclass.gettraitnames.php
*
* A partial reflection also names the traits that can not be located, as written in the source of the class: they
* are left out of getTraits() only.
*/
public function getTraitNames(): array
{
return array_keys($this->getTraits());
if (!$this->isPartial()) {
return array_keys($this->getTraits());
}
[, , $traitNames] = $this->getAncestorNamesFromSource();

return $traitNames;
}

/**
* Returns the names of the parent class, interfaces and traits as written in the source of the class
*
* The names are resolved from the class node only: an ancestor is listed whether it can be located or not.
*
* @return array{string|null, list<string>, list<string>} Parent class (null if none), interfaces and traits
*/
private function getAncestorNamesFromSource(): array
{
$resolveNames = static function (array $nameNodes): array {
$names = [];
foreach ($nameNodes as $nameNode) {
$resolvedName = $nameNode instanceof Name ? $nameNode->getAttribute('resolvedName') : null;
if ($resolvedName instanceof FullyQualified) {
$names[] = $resolvedName->toString();
}
}

return $names;
};

$classLikeNode = $this->classLikeNode;
$parentNames = $classLikeNode instanceof Class_ && $classLikeNode->extends !== null
? $resolveNames([$classLikeNode->extends])
: [];
$interfaceNodes = match (true) {
$classLikeNode instanceof Interface_ => $classLikeNode->extends,
$classLikeNode instanceof Class_, $classLikeNode instanceof Enum_ => $classLikeNode->implements,
default => [],
};
$traitNames = [];
foreach ($classLikeNode->stmts as $classLevelNode) {
if ($classLevelNode instanceof TraitUse) {
array_push($traitNames, ...$resolveNames($classLevelNode->traits));
}
}

return [$parentNames[0] ?? null, $resolveNames($interfaceNodes), array_values(array_unique($traitNames))];
}

/**
Expand Down Expand Up @@ -811,12 +901,13 @@ public function hasProperty(string $name): bool
public function implementsInterface(\ReflectionClass|string $interfaceName): bool
{
$allInterfaces = $this->getInterfaces();

if ($interfaceName instanceof \ReflectionClass) {
return isset($allInterfaces[$interfaceName->getName()]);
} else {
return isset($allInterfaces[$interfaceName]);
$interfaceName = $interfaceName->getName();
}

// An interface that can not be located is known from the source only, see getInterfaceNames()
return isset($allInterfaces[$interfaceName])
|| ($this->isPartial() && in_array($interfaceName, $this->getInterfaceNames(), true));
}

/**
Expand Down
37 changes: 31 additions & 6 deletions tests/PartialReflectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,16 +113,38 @@ public function testOwnDeclarationsOfAPartialClassAreAvailable(): void
$this->assertSame(self::MISSING_PARENT, $node->extends?->getAttribute('resolvedName')?->toString());
}

public function testNamesOfMissingAncestorsAreKnownFromTheSource(): void
{
$this->initEngine(MissingAncestorPolicy::Partial);
$class = new ReflectionClass(self::PARTIAL_CLASS);

$this->assertSame(self::MISSING_PARENT, $class->getParentClassName());
$this->assertSame([self::AVAILABLE_IFACE, self::MISSING_INTERFACE], $class->getInterfaceNames());
$this->assertTrue($class->implementsInterface(self::AVAILABLE_IFACE));
$this->assertTrue($class->implementsInterface(self::MISSING_INTERFACE));
$this->assertFalse($class->implementsInterface(\Countable::class));
$this->assertSame([self::AVAILABLE_TRAIT, self::MISSING_TRAIT], $class->getTraitNames());
}

public function testParentClassNameIsReadFromTheSource(): void
{
foreach (MissingAncestorPolicy::cases() as $policy) {
$this->initEngine($policy);

$this->assertSame(\ArrayObject::class, (new ReflectionClass(self::COMPLETE_CLASS))->getParentClassName());
$this->assertSame(self::PARTIAL_CLASS, (new ReflectionClass(self::CHILD_CLASS))->getParentClassName());
$this->assertFalse((new ReflectionClass(self::AVAILABLE_IFACE))->getParentClassName());
}
}

public function testMissingAncestorsAreLeftOutOfAPartialClass(): void
{
$this->initEngine(MissingAncestorPolicy::Partial);
$class = new ReflectionClass(self::PARTIAL_CLASS);

$this->assertFalse($class->getParentClass());
$this->assertSame([self::AVAILABLE_IFACE], $class->getInterfaceNames());
$this->assertTrue($class->implementsInterface(self::AVAILABLE_IFACE));
$this->assertFalse($class->implementsInterface(self::MISSING_INTERFACE));
$this->assertSame([self::AVAILABLE_TRAIT], $class->getTraitNames());
$this->assertSame([self::AVAILABLE_IFACE], array_keys($class->getInterfaces()));
$this->assertSame([self::AVAILABLE_TRAIT], array_keys($class->getTraits()));
// The class declares these ancestors directly, so this is known from its source
$this->assertTrue($class->isSubclassOf(self::MISSING_PARENT));
$this->assertTrue($class->isSubclassOf(self::MISSING_INTERFACE));
Expand Down Expand Up @@ -152,7 +174,9 @@ public function testMissingAncestorsOfAnAvailableAncestorAreReported(): void
$this->names($class->getMethods())
);
$this->assertTrue($class->isSubclassOf(self::PARTIAL_CLASS));
$this->assertSame([self::AVAILABLE_IFACE], $class->getInterfaceNames());
// The interface missing for the parent class is named through it
$this->assertSame([self::AVAILABLE_IFACE, self::MISSING_INTERFACE], $class->getInterfaceNames());
$this->assertTrue($class->implementsInterface(self::MISSING_INTERFACE));
}

public function testInterfaceWithAMissingParentInterfaceIsPartial(): void
Expand All @@ -162,7 +186,8 @@ public function testInterfaceWithAMissingParentInterfaceIsPartial(): void

$this->assertTrue($interface->isPartial());
$this->assertSame([self::MISSING_INTERFACE], $interface->getMissingClassNames());
$this->assertSame([self::AVAILABLE_IFACE], $interface->getInterfaceNames());
$this->assertSame([self::AVAILABLE_IFACE], array_keys($interface->getInterfaces()));
$this->assertSame([self::AVAILABLE_IFACE, self::MISSING_INTERFACE], $interface->getInterfaceNames());
$this->assertSame(['availableInterfaceMethod'], $this->names($interface->getMethods()));
}

Expand Down
Loading