diff --git a/CLAUDE.md b/CLAUDE.md index 6d10e60..1a7b844 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 diff --git a/README.md b/README.md index e6723a3..2bfa946 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/docs/reflection_class.md b/docs/reflection_class.md index b246b82..1c67b3d 100644 --- a/docs/reflection_class.md +++ b/docs/reflection_class.md @@ -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 diff --git a/src/ClassNotFoundException.php b/src/ClassNotFoundException.php new file mode 100644 index 0000000..14945e8 --- /dev/null +++ b/src/ClassNotFoundException.php @@ -0,0 +1,26 @@ + + * + * 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"); + } +} diff --git a/src/MissingAncestorPolicy.php b/src/MissingAncestorPolicy.php new file mode 100644 index 0000000..e495ce4 --- /dev/null +++ b/src/MissingAncestorPolicy.php @@ -0,0 +1,40 @@ + + * + * 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; +} diff --git a/src/ReflectionClass.php b/src/ReflectionClass.php index d54887d..b9dc647 100644 --- a/src/ReflectionClass.php +++ b/src/ReflectionClass.php @@ -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> 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; } } @@ -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 $traitAdaptations List of method adaptations * * @return \ReflectionClass[] 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 + */ + 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|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 + */ + 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 + */ + 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. * @@ -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 The appropriate reflection object. - */ - protected function createReflectionForClass(string $className): InternalReflectionClass - { - return class_exists($className, false) ? new parent($className) : new self($className); - } } diff --git a/src/ReflectionEngine.php b/src/ReflectionEngine.php index 538cc03..c5c4a39 100644 --- a/src/ReflectionEngine.php +++ b/src/ReflectionEngine.php @@ -57,6 +57,11 @@ class ReflectionEngine */ private static ?PhpVersion $phpVersion = null; + /** + * What the reflection of a class does when one of its ancestors can not be located + */ + private static MissingAncestorPolicy $missingAncestorPolicy = MissingAncestorPolicy::Strict; + private function __construct() {} /** @@ -68,14 +73,41 @@ private function __construct() {} * The parser is created on the first parse: the composer bootstrap of this package initializes the engine on * every request of an application, and most of them never parse anything. * - * @param PhpVersion|null $phpVersion Optional PHP version of the grammar to parse sources with + * @param PhpVersion|null $phpVersion Optional PHP version of the grammar to parse sources with + * @param MissingAncestorPolicy $missingAncestorPolicy What the reflection of a class does when one of its + * ancestors can not be located, strict by default + */ + public static function init( + LocatorInterface $locator, + ?PhpVersion $phpVersion = null, + MissingAncestorPolicy $missingAncestorPolicy = MissingAncestorPolicy::Strict + ): void { + self::$locator = $locator; + self::$phpVersion = $phpVersion; + self::$missingAncestorPolicy = $missingAncestorPolicy; + self::$parser = null; + self::$traverser = null; + } + + /** + * Sets what the reflection of a class does when one of its ancestors can not be located + * + * With the strict policy (the default) every method that needs a missing ancestor throws. With the partial + * policy missing ancestors are left out, and the reflection reports itself as partial. + * + * @see ReflectionClass::isPartial() + */ + public static function setMissingAncestorPolicy(MissingAncestorPolicy $missingAncestorPolicy): void + { + self::$missingAncestorPolicy = $missingAncestorPolicy; + } + + /** + * Returns what the reflection of a class does when one of its ancestors can not be located */ - public static function init(LocatorInterface $locator, ?PhpVersion $phpVersion = null): void + public static function getMissingAncestorPolicy(): MissingAncestorPolicy { - self::$locator = $locator; - self::$phpVersion = $phpVersion; - self::$parser = null; - self::$traverser = null; + return self::$missingAncestorPolicy; } /** @@ -91,6 +123,8 @@ public static function setMaximumCachedFiles(int $newLimit): void /** * Locates a file name for class + * + * @throws ClassNotFoundException If the class is not declared and the locator can not find its file */ public static function locateClassFile(string $fullClassName): string { @@ -110,9 +144,13 @@ public static function locateClassFile(string $fullClassName): string throw new \LogicException('ReflectionEngine locator is not initialized. Call ReflectionEngine::init() first.'); } $classFileName = self::$locator->locateClass($fullClassName); + if (!$classFileName) { + throw new ClassNotFoundException($fullClassName); + } } if (!$classFileName) { + // An internal class has no file throw new InvalidArgumentException("Class $fullClassName was not found by locator"); } diff --git a/src/Traits/ReflectionClassLikeTrait.php b/src/Traits/ReflectionClassLikeTrait.php index 31c62ac..da00380 100644 --- a/src/Traits/ReflectionClassLikeTrait.php +++ b/src/Traits/ReflectionClassLikeTrait.php @@ -109,6 +109,13 @@ trait ReflectionClassLikeTrait */ protected ?array $classConstants; + /** + * Names of the ancestors that can not be located, or null if not initialized yet + * + * @var list|null + */ + protected ?array $missingClassNames; + /** * Returns the string representation of the ReflectionClass object. */ @@ -511,9 +518,44 @@ public function getNamespaceName(): string return $this->namespaceName; } + /** + * Returns the names of the ancestors (parent class, interfaces and traits) that can not be located + * + * The ancestors missing for the available ancestors are included as well. With the partial + * {@see \Go\ParserReflection\MissingAncestorPolicy} these ancestors are left out of the reflection, with the + * strict one every method that needs them throws. This method itself never throws for a missing ancestor. + * + * @return list + */ + public function getMissingClassNames(): array + { + if (!isset($this->missingClassNames)) { + $this->missingClassNames = ReflectionClass::collectMissingAncestorNames($this->classLikeNode); + } + + return $this->missingClassNames; + } + + /** + * Checks whether some ancestors (parent class, interfaces or traits) of the class can not be located + * + * The reflection of such a class only covers what the class and its available ancestors declare: inherited + * members, the parent class, interfaces and traits that come from a missing ancestor are left out with the + * partial {@see \Go\ParserReflection\MissingAncestorPolicy}. + * + * @see getMissingClassNames() + */ + public function isPartial(): bool + { + return $this->getMissingClassNames() !== []; + } + /** * {@inheritDoc} * + * With the partial {@see \Go\ParserReflection\MissingAncestorPolicy}, false is returned for a parent class that + * can not be located. + * * @return \ReflectionClass|false */ public function getParentClass(): \ReflectionClass|false @@ -525,7 +567,7 @@ public function getParentClass(): \ReflectionClass|false if ($extendsNode instanceof Name && $extendsNode->getAttribute('resolvedName') instanceof FullyQualified) { $extendsName = $extendsNode->getAttribute('resolvedName')->toString(); - $parentClass = $this->createReflectionForClass($extendsName); + $parentClass = ReflectionClass::reflectAncestor($extendsName) ?? false; } $this->parentClass = $parentClass; } @@ -1397,18 +1439,4 @@ private function wrapInheritedMethod(\ReflectionMethod $method, string $contextC return $method; } - - /** - * Create a ReflectionClass for a given class name. - * - * @param string $className The name of the class to create a reflection for. - * - * @return \ReflectionClass The appropriate reflection object. - */ - protected function createReflectionForClass(string $className): \ReflectionClass - { - return class_exists($className, false) - ? new \ReflectionClass($className) - : new ReflectionClass($className); - } } diff --git a/tests/PartialReflectionTest.php b/tests/PartialReflectionTest.php new file mode 100644 index 0000000..8ad7598 --- /dev/null +++ b/tests/PartialReflectionTest.php @@ -0,0 +1,222 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Go\ParserReflection; + +use Go\ParserReflection\Locator\CallableLocator; +use Go\ParserReflection\Locator\ComposerLocator; +use InvalidArgumentException; +use PhpParser\Node\Stmt\Class_; +use PHPUnit\Framework\TestCase; + +/** + * A class whose ancestors can not be located is reflected partially with the partial policy + * + * @see https://github.com/goaop/parser-reflection/issues/251 + */ +final class PartialReflectionTest extends TestCase +{ + private const string STUB_FILE = __DIR__ . '/Stub/FileWithMissingAncestors.php'; + private const string NS = 'Go\ParserReflection\Stub\MissingAncestors\\'; + private const string AVAILABLE_IFACE = self::NS . 'AvailableInterface'; + private const string AVAILABLE_TRAIT = self::NS . 'AvailableTrait'; + private const string PARTIAL_CLASS = self::NS . 'ClassWithMissingAncestors'; + private const string CHILD_CLASS = self::NS . 'ChildOfClassWithMissingAncestors'; + private const string PARTIAL_INTERFACE = self::NS . 'InterfaceWithMissingParent'; + private const string COMPLETE_CLASS = self::NS . 'ClassWithAvailableAncestors'; + private const string MISSING_PARENT = self::NS . 'Generated\MissingParent'; + private const string MISSING_INTERFACE = self::NS . 'Generated\MissingInterface'; + private const string MISSING_TRAIT = self::NS . 'Generated\MissingTrait'; + + protected function tearDown(): void + { + // Restores the default locator and the strict policy for the following tests + ReflectionEngine::init(new ComposerLocator()); + } + + public function testStrictPolicyIsTheDefault(): void + { + ReflectionEngine::init(new ComposerLocator()); + + $this->assertSame(MissingAncestorPolicy::Strict, ReflectionEngine::getMissingAncestorPolicy()); + } + + public function testPolicyIsSetByInitAndBySetter(): void + { + ReflectionEngine::init(new ComposerLocator(), null, MissingAncestorPolicy::Partial); + $this->assertSame(MissingAncestorPolicy::Partial, ReflectionEngine::getMissingAncestorPolicy()); + + ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Strict); + $this->assertSame(MissingAncestorPolicy::Strict, ReflectionEngine::getMissingAncestorPolicy()); + + ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Partial); + ReflectionEngine::init(new ComposerLocator()); + $this->assertSame(MissingAncestorPolicy::Strict, ReflectionEngine::getMissingAncestorPolicy()); + } + + public function testStrictPolicyThrowsForAMissingAncestor(): void + { + $this->initEngine(MissingAncestorPolicy::Strict); + $class = new ReflectionClass(self::PARTIAL_CLASS); + + try { + $class->getMethods(); + $this->fail('A missing ancestor must be reported with the strict policy'); + } catch (ClassNotFoundException $e) { + $this->assertInstanceOf(InvalidArgumentException::class, $e); + $this->assertContains($e->className, [self::MISSING_PARENT, self::MISSING_INTERFACE, self::MISSING_TRAIT]); + $this->assertSame('Class ' . $e->className . ' was not found by locator', $e->getMessage()); + } + } + + public function testMissingAncestorsAreReportedWithTheStrictPolicyWithoutThrowing(): void + { + $this->initEngine(MissingAncestorPolicy::Strict); + $class = new ReflectionClass(self::PARTIAL_CLASS); + + $this->assertTrue($class->isPartial()); + $this->assertSame([self::MISSING_PARENT, self::MISSING_INTERFACE, self::MISSING_TRAIT], $class->getMissingClassNames()); + } + + public function testOwnDeclarationsOfAPartialClassAreAvailable(): void + { + $this->initEngine(MissingAncestorPolicy::Partial); + $class = new ReflectionClass(self::PARTIAL_CLASS); + + $this->assertTrue($class->isPartial()); + $this->assertSame([self::MISSING_PARENT, self::MISSING_INTERFACE, self::MISSING_TRAIT], $class->getMissingClassNames()); + + $this->assertSame(self::PARTIAL_CLASS, $class->getName()); + $this->assertFalse($class->isFinal()); + $this->assertFalse($class->isAbstract()); + $this->assertSame(['ownMethod', 'availableInterfaceMethod', 'availableTraitMethod'], $this->names($class->getMethods())); + $this->assertTrue($class->hasMethod('ownMethod')); + $this->assertSame(['ownProperty'], $this->names($class->getProperties())); + $this->assertSame(['OWN_CONSTANT' => 42, 'INTERFACE_CONSTANT' => 'interface'], $class->getConstants()); + $this->assertSame([self::NS . 'Marker'], array_map( + static fn (\ReflectionAttribute $attribute): string => $attribute->getName(), + $class->getAttributes() + )); + + // Names of the ancestors as written stay available from the node + $node = $class->getNode(); + $this->assertInstanceOf(Class_::class, $node); + $this->assertSame(self::MISSING_PARENT, $node->extends?->getAttribute('resolvedName')?->toString()); + } + + 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()); + // 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)); + + $method = $class->getMethod('availableInterfaceMethod'); + $this->assertTrue($method->hasPrototype()); + $this->assertSame(self::AVAILABLE_IFACE, $method->getPrototype()->getDeclaringClass()->getName()); + $this->assertFalse($class->getMethod('ownMethod')->hasPrototype()); + + $this->assertStringContainsString('Class [ class ' . self::PARTIAL_CLASS . ' implements ' . self::AVAILABLE_IFACE, (string) $class); + } + + public function testMissingAncestorsOfAnAvailableAncestorAreReported(): void + { + $this->initEngine(MissingAncestorPolicy::Partial); + $class = new ReflectionClass(self::CHILD_CLASS); + + $this->assertTrue($class->isPartial()); + $this->assertSame([self::MISSING_PARENT, self::MISSING_INTERFACE, self::MISSING_TRAIT], $class->getMissingClassNames()); + + $parentClass = $class->getParentClass(); + $this->assertInstanceOf(ReflectionClass::class, $parentClass); + $this->assertSame(self::PARTIAL_CLASS, $parentClass->getName()); + $this->assertTrue($parentClass->isPartial()); + $this->assertSame( + ['childMethod', 'ownMethod', 'availableInterfaceMethod', 'availableTraitMethod'], + $this->names($class->getMethods()) + ); + $this->assertTrue($class->isSubclassOf(self::PARTIAL_CLASS)); + $this->assertSame([self::AVAILABLE_IFACE], $class->getInterfaceNames()); + } + + public function testInterfaceWithAMissingParentInterfaceIsPartial(): void + { + $this->initEngine(MissingAncestorPolicy::Partial); + $interface = new ReflectionClass(self::PARTIAL_INTERFACE); + + $this->assertTrue($interface->isPartial()); + $this->assertSame([self::MISSING_INTERFACE], $interface->getMissingClassNames()); + $this->assertSame([self::AVAILABLE_IFACE], $interface->getInterfaceNames()); + $this->assertSame(['availableInterfaceMethod'], $this->names($interface->getMethods())); + } + + public function testClassWithAvailableAncestorsIsNotPartial(): void + { + foreach (MissingAncestorPolicy::cases() as $policy) { + $this->initEngine($policy); + $class = new ReflectionClass(self::COMPLETE_CLASS); + + $this->assertFalse($class->isPartial()); + $this->assertSame([], $class->getMissingClassNames()); + $this->assertSame(\ArrayObject::class, $class->getParentClass()->getName()); + $this->assertTrue($class->implementsInterface(\Countable::class)); + } + } + + public function testClassesOfAParsedFileAreReflectedPartially(): void + { + $this->initEngine(MissingAncestorPolicy::Partial); + $file = new ReflectionFile(self::STUB_FILE); + $class = $file->getFileNamespace(rtrim(self::NS, '\\'))->getClass(self::PARTIAL_CLASS); + + $this->assertTrue($class->isPartial()); + $this->assertSame(['ownMethod', 'availableInterfaceMethod', 'availableTraitMethod'], $this->names($class->getMethods())); + } + + public function testMissingClassItselfStillThrowsWithThePartialPolicy(): void + { + $this->initEngine(MissingAncestorPolicy::Partial); + + $this->expectException(ClassNotFoundException::class); + new ReflectionClass(self::MISSING_PARENT); + } + + /** + * Locates every class of the stub file, except the ones of the Generated namespace + */ + private function initEngine(MissingAncestorPolicy $policy): void + { + $locator = new CallableLocator(static function (string $className): string|false { + $isStubClass = str_starts_with($className, self::NS) && !str_starts_with($className, self::NS . 'Generated\\'); + + return $isStubClass ? self::STUB_FILE : false; + }); + ReflectionEngine::init($locator, null, $policy); + } + + /** + * @param array<\ReflectionMethod|\ReflectionProperty> $reflections + * + * @return list + */ + private function names(array $reflections): array + { + return array_values(array_map(static fn (\Reflector $reflection): string => $reflection->getName(), $reflections)); + } +} diff --git a/tests/Stub/FileWithMissingAncestors.php b/tests/Stub/FileWithMissingAncestors.php new file mode 100644 index 0000000..898571c --- /dev/null +++ b/tests/Stub/FileWithMissingAncestors.php @@ -0,0 +1,73 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ +declare(strict_types=1); + +namespace Go\ParserReflection\Stub\MissingAncestors; + +use Go\ParserReflection\Stub\MissingAncestors\Generated\MissingInterface; +use Go\ParserReflection\Stub\MissingAncestors\Generated\MissingParent; +use Go\ParserReflection\Stub\MissingAncestors\Generated\MissingTrait; + +/* + * The ancestors from the Generated namespace are never declared and can not be located: this file is only parsed, + * it must never be included + */ + +interface AvailableInterface +{ + public const INTERFACE_CONSTANT = 'interface'; + + public function availableInterfaceMethod(): void; +} + +trait AvailableTrait +{ + public function availableTraitMethod(): void + { + } +} + +#[Marker] +class ClassWithMissingAncestors extends MissingParent implements AvailableInterface, MissingInterface +{ + use AvailableTrait, MissingTrait; + + public const OWN_CONSTANT = 42; + + public int $ownProperty = 1; + + public function ownMethod(): void + { + } + + public function availableInterfaceMethod(): void + { + } +} + +class ChildOfClassWithMissingAncestors extends ClassWithMissingAncestors +{ + public function childMethod(): void + { + } +} + +interface InterfaceWithMissingParent extends AvailableInterface, MissingInterface +{ +} + +class ClassWithAvailableAncestors extends \ArrayObject implements AvailableInterface +{ + use AvailableTrait; + + public function availableInterfaceMethod(): void + { + } +}