From e2e9762bd3de896a19d156de298cae9e2ae73273 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 22:05:29 +0000 Subject: [PATCH 1/4] feat(weaving): weave classes whose ancestors can not be located A class whose parent class, interface or trait is declared by code generated at runtime, by a class_alias() or outside the Composer autoloader failed the whole file (and cache:warmup:aop), even when no pointcut could match it: matching walks every method, inherited ones included. goaop/parser-reflection 4.1/5.1 can reflect such a class partially. AdviceMatcher::getAdvicesForClass() now switches it to MissingAncestorPolicy::Partial before any pointcut walks the ancestors, so cache hits never pay for it. The class is matched and woven with its own members and the ones of its available ancestors. A partial reflection leaves missing ancestors out of getParentClass() and getInterfaceNames(), which the proxy generators re-declare: the class and enum proxies now add the missing parent class and interfaces under the names resolved from the source, otherwise the proxy would lose them. Requires goaop/parser-reflection ^4.1.0 || ^5.1.0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FxhC1CBg4rnTu9UjAMcCpL --- CHANGELOG.md | 3 +- composer.json | 2 +- src/Aop/Exception/WeavingException.php | 8 ++- src/Core/AGENTS.md | 2 + src/Core/AdviceMatcher.php | 6 ++ src/Instrument/AGENTS.md | 15 +++- .../Transformer/WeavingTransformer.php | 4 +- src/Proxy/ClassProxyGenerator.php | 66 ++++++++++++++++- src/Proxy/EnumProxyGenerator.php | 4 +- tests/Aop/Exception/ExceptionMessagesTest.php | 8 +-- tests/Core/AdviceMatcherTest.php | 32 +++++++++ .../Application/Issue251ReportController.php | 27 +++++++ .../project/src/Aspect/Issue251Aspect.php | 36 ++++++++++ .../src/Kernel/DefaultAspectKernel.php | 2 + tests/Functional/BaseFunctionalTestCase.php | 32 +++++++++ .../Functional/InheritedMethodWeavingTest.php | 34 --------- .../PartialReflectionWeavingTest.php | 70 +++++++++++++++++++ .../Transformer/WeavingTransformerTest.php | 46 ++++++++++++ .../_files/enum-unknown-interface.php | 20 ++++++ tests/Proxy/EnumProxyGeneratorTest.php | 29 ++++++++ 20 files changed, 396 insertions(+), 50 deletions(-) create mode 100644 tests/Fixtures/project/src/Application/Issue251ReportController.php create mode 100644 tests/Fixtures/project/src/Aspect/Issue251Aspect.php create mode 100644 tests/Functional/PartialReflectionWeavingTest.php create mode 100644 tests/Instrument/Transformer/_files/enum-unknown-interface.php diff --git a/CHANGELOG.md b/CHANGELOG.md index a5133f64..1162e514 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ See [UPGRADE-4.0.md](UPGRADE-4.0.md) for the migration guide. **Requirements** * [BC BREAK] Requires PHP 8.4+ -* [BC BREAK] **Dependencies** — `ext-tokenizer`, `goaop/parser-reflection` ^4.0.2 || ^5.0.2, `goaop/dissect` ^4.0, `psr/container` ^1.1 || ^2.0 and `symfony/finder` ^7.4 || ^8.0. `nikic/php-parser` 5 comes through parser-reflection and is no longer required directly. `symfony/console` ^7.4 || ^8.0 is needed for the `bin/aspect` tool. +* [BC BREAK] **Dependencies** — `ext-tokenizer`, `goaop/parser-reflection` ^4.1.0 || ^5.1.0, `goaop/dissect` ^4.0, `psr/container` ^1.1 || ^2.0 and `symfony/finder` ^7.4 || ^8.0. `nikic/php-parser` 5 comes through parser-reflection and is no longer required directly. `symfony/console` ^7.4 || ^8.0 is needed for the `bin/aspect` tool. **Added** * [Feature] **First-class callable advices** — the main way advices are now wired into woven code. Generated proxies declare each aspect-method advice as `Interceptor::before(The::aspect(MonitorAspect::class)->beforeMethodExecution(...))` — an eager first-class callable, since the interceptor list is only built while the intercepted method or hook is already executing (`LazyAdvisorAccessor` is removed). Compiled advisor cache files use the same facade in its lazy static-data form, e.g. `Interceptor::before(MonitorAspect::class, 'beforeMethodExecution')`, which returns a native PHP lazy proxy: interceptor construction, aspect resolution from the container and advice callable creation are all deferred until the advice is actually used, so cached advices whose pointcut never matches never instantiate their aspect. Advices registered in the container as plain closures (not aspect methods) are resolved through the new `The::advice('advisorId')` accessor, which unwraps `Advisor` and interceptor values down to the raw advice closure. @@ -27,6 +27,7 @@ See [UPGRADE-4.0.md](UPGRADE-4.0.md) for the migration guide. * [Feature] **Cache warm-up into another directory** — `new CacheWarmer($kernel, cacheDir: $dir)` and `cache:warmup:aop --cache-dir=DIR` (also with `--workers`) build the cache in a directory other than the one of the kernel, from scratch, while the kernel keeps serving the process from its own directory (`CachePathManager::withCacheDir()`): a deployment prepares the cache of the next release next to the running one, the way Symfony's `cache:clear` warms a new cache directory up before swapping it in. Woven sources served while such a build runs include their proxies from the directory being built. * [Feature] [BC BREAK] **Doctrine bridge rewritten for the trait-based engine (#671)** — new `Go\Bridge\Doctrine\WovenEntityClassLocator` lets Doctrine mapping drivers (ORM 3.6+) discover entities through the autoloader, so the woven class is mapped instead of the original source, and entities loaded before discovery are no longer missed. `MetadataLoadInterceptor` no longer rewrites metadata (the old mapped-superclass workaround only matched the extend-based engine); it now reports woven entities with intercepted mapped properties when Doctrine native lazy objects are disabled. It is registered as a plain listener: `$eventManager->addEventListener(Events::loadClassMetadata, new MetadataLoadInterceptor())` (it is no longer an `EventSubscriber`). * [Feature] **Aspects whose creation runs their own advices are reported** — the container marks a deferred service while its factory runs, and an interceptor about to run an advice of an aspect being created throws the new `Go\Aop\Exception\AspectCircularReferenceException` (a `RuntimeException` implementing PSR `ContainerExceptionInterface`) with the aspect, the joinpoint and the calls from the creation to the advice, e.g. `ClockAspect -> Scheduler->__construct() -> Clock->now() -> ClockAspect->beforeNow()`. Such an advice used to run on the half-initialized lazy aspect: PHP reported an uninitialized property at best, an advice reading no property ran without any error (#783). +* [Feature] **Classes with ancestors Composer can not locate are woven** — the weaver reflects classes with the partial policy of goaop/parser-reflection 4.1/5.1 (`MissingAncestorPolicy::Partial`): a parent class, interface or trait declared by code generated at runtime, by a `class_alias()` or in a file outside the Composer autoloader no longer fails the file (and `cache:warmup:aop`). The class is matched and woven with its own methods and properties and the ones of its available ancestors; members inherited from a missing ancestor are not intercepted. The proxy still declares the missing parent class and interfaces, which must be loaded by the time the class is. The policy is switched on by `AdviceMatcher::getAdvicesForClass()`, so requests served from the cache never reflect. * [Feature] **Hint for classes Composer can not locate** — when weaving fails because goaop/parser-reflection can not find the source of a parent class, interface or trait (code generated at runtime, a `class_alias()`, a file outside the Composer autoloader), the `WeavingException` tells how to make the class loadable or to exclude the classes depending on it with `excludePaths` (#782). **Changed** diff --git a/composer.json b/composer.json index b172e859..19943548 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,7 @@ "php": "^8.4.0", "ext-tokenizer": "*", "goaop/dissect": "^4.0", - "goaop/parser-reflection": "^4.0.2 || ^5.0.2", + "goaop/parser-reflection": "^4.1.0 || ^5.1.0", "psr/container": "^1.1 || ^2.0", "symfony/finder": "^7.4 || ^8.0" }, diff --git a/src/Aop/Exception/WeavingException.php b/src/Aop/Exception/WeavingException.php index 866f4965..9a62ffeb 100644 --- a/src/Aop/Exception/WeavingException.php +++ b/src/Aop/Exception/WeavingException.php @@ -51,7 +51,7 @@ public static function transformerFailed(string $transformerClass, string $uri, $missing = self::unlocatableClass($previous); if ($missing !== null) { $message = sprintf( - '%s. The weaver reads the parents, interfaces and traits of a class from their source files, which it ' + '%s. The weaver reads the classes a woven class depends on from their source files, which it ' . 'finds through Composer: make %s loadable by Composer (classmap, PSR-4 or $loader->addClassMap() ' . 'before the aspect kernel is initialized), or exclude the classes that depend on it from weaving ' . 'with the excludePaths option.', @@ -196,8 +196,10 @@ public static function functionReturnsByReference(string $functionName): self /** * Name of the class that goaop/parser-reflection could not find the source of, found in the exception chain * - * A class whose ancestor is declared by code generated at runtime, by a class_alias() or in a file Composer - * does not know can not be reflected from the source files. + * A class declared by code generated at runtime, by a class_alias() or in a file Composer does not know can not be + * reflected from the source files. A missing ancestor is left out of the partial reflection the weaver uses, but + * a file that does not declare the class it was located for, or a class used in a constant expression, still + * fails. */ private static function unlocatableClass(Throwable $exception): ?string { diff --git a/src/Core/AGENTS.md b/src/Core/AGENTS.md index 629b6b30..d5a0281f 100644 --- a/src/Core/AGENTS.md +++ b/src/Core/AGENTS.md @@ -22,6 +22,8 @@ - Lives in the nested Go\Core\Cache namespace (CachedAspectLoader, AdvisorCacheCompiler, AdvisorCachePrinter, CacheFileWriter — all @internal); format, naming and error-handling rules: see src/Core/Cache/AGENTS.md - AttributeAspectLoaderExtension — handles PHP 8 attribute-based aspect definitions; throws AspectException for non-public advice methods (first-class callable advices require public visibility; #[Pointcut]-only methods exempt) - AdviceMatcher — given class reflector, returns applicable advisors keyed by join point + - getAdvicesForClass() first switches goaop/parser-reflection to `MissingAncestorPolicy::Partial`: ancestors that can't be + located are left out instead of failing the class (src/Instrument/AGENTS.md § Partial reflection) - Scans IS_PUBLIC|IS_PROTECTED|IS_PRIVATE methods - Private methods from parent classes excluded - Inherited methods (`$method->class` is a parent; trait methods name the class itself): skipped per advisor when an diff --git a/src/Core/AdviceMatcher.php b/src/Core/AdviceMatcher.php index a698a4ac..d6a40f58 100644 --- a/src/Core/AdviceMatcher.php +++ b/src/Core/AdviceMatcher.php @@ -19,6 +19,8 @@ use Go\Aop\Pointcut; use Go\Aop\Proxy; use Go\Instrument\PathResolver; +use Go\ParserReflection\MissingAncestorPolicy; +use Go\ParserReflection\ReflectionEngine; use Go\ParserReflection\ReflectionFileNamespace; use ReflectionClass; use ReflectionFunction; @@ -98,6 +100,10 @@ public function getAdvicesForFunctions(ReflectionFileNamespace $namespace, array */ public function getAdvicesForClass(ReflectionClass $class, array $advisors): array { + // Classes are matched, then woven, with partial reflection: an ancestor declared in code generated at runtime, + // by a class_alias() or outside the Composer autoloader is left out instead of failing the class. Switched on + // here, before any pointcut walks the ancestors, so that requests served from the cache never pay for it + ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Partial); $classAdvices = []; foreach ($advisors as $advisorId => $advisor) { diff --git a/src/Instrument/AGENTS.md b/src/Instrument/AGENTS.md index 8e45d4aa..3c6f45ce 100644 --- a/src/Instrument/AGENTS.md +++ b/src/Instrument/AGENTS.md @@ -112,5 +112,18 @@ WeavingException). Details and workarounds: src/Instrument/Transformer/Weaving/A ## Aspects themselves Classes implementing \Go\Aop\Aspect: unconditionally skipped by WeavingTransformer. Aspects cannot weave themselves. The check (`implementsInterface(Aspect::class)`) runs in WeavingTransformer::weaveClass() only AFTER advices were found: it reflects -(and parses) every ancestor and throws when one can't be located, so unadvised classes must never pay for it (#748). +(and parses) every ancestor, so unadvised classes must never pay for it (#748). + +## Partial reflection: ancestors that can't be located +AdviceMatcher::getAdvicesForClass() sets `ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Partial)` +(goaop/parser-reflection 4.1/5.1) as its first statement: a parent class, interface or trait whose source the locator +can't find (generated at runtime, `class_alias()`, outside the Composer autoloader) is left out of the reflection instead +of failing the class. Not in AspectKernel::init() (cache hits never reflect), not in the AdviceMatcher service factory (a +native lazy proxy initializes on the first property access, after `$pointcut->matches()` may have walked the ancestors). +Consequences: +- Matching sees the class's own members and the ones of its available ancestors; members inherited from a missing ancestor + are never matched, so never intercepted. +- The proxy must still declare the missing parent/interfaces: ClassProxyGenerator::getMissingDeclaredAncestors() adds the + direct ones (`isPartial()`/`getMissingClassNames()` ∩ names resolved from the class node) to `extends`/`implements`. + Ancestors missing further up come with the available ancestor. Missing traits need nothing: the `use` stays in the trait body. A matching failure on an aspect is swallowed (aspects used to be skipped before matching); on other classes it is rethrown. diff --git a/src/Instrument/Transformer/WeavingTransformer.php b/src/Instrument/Transformer/WeavingTransformer.php index 079e8d7f..0ba53b45 100644 --- a/src/Instrument/Transformer/WeavingTransformer.php +++ b/src/Instrument/Transformer/WeavingTransformer.php @@ -85,7 +85,7 @@ public function transform(StreamMetaData $metadata): TransformerResult $this->cachePathManager->registerClassForResource($metadata->uri, $class->getName()); // Skip interfaces — enums are supported via EnumProxyGenerator. Aspects are skipped - // in weaveClass() once advices were found: the check reflects every ancestor + // in weaveClass() once advices were found: the check reflects (and parses) every ancestor if ($class->isInterface()) { continue; } @@ -135,7 +135,7 @@ private function weaveClass( if ($advices === []) { // Fast return if there aren't any advices for that class. It comes before the aspect check, - // as that one reflects (and parses) every ancestor and fails when one can't be located + // as that one reflects (and parses) every ancestor return null; } diff --git a/src/Proxy/ClassProxyGenerator.php b/src/Proxy/ClassProxyGenerator.php index aa912651..96574721 100644 --- a/src/Proxy/ClassProxyGenerator.php +++ b/src/Proxy/ClassProxyGenerator.php @@ -27,6 +27,8 @@ use Go\Aop\Proxy; use Go\Aop\StaticInitializationAware; use Go\Core\AspectContainer; +use Go\ParserReflection\ReflectionClass as ParsedReflectionClass; +use Go\ParserReflection\ReflectionEnum as ParsedReflectionEnum; use Go\Proxy\Generator\AttributeGroupsGenerator; use Go\Proxy\Generator\ClassGenerator; use Go\Proxy\Generator\ClassModifier; @@ -51,9 +53,12 @@ use PhpParser\Node\Expr\StaticCall; use PhpParser\Node\Expr\Variable; use PhpParser\Node\Name; +use PhpParser\Node\Name\FullyQualified; use PhpParser\Node\Scalar\String_; use PhpParser\Node\Stmt; +use PhpParser\Node\Stmt\Class_; use PhpParser\Node\Stmt\ClassMethod; +use PhpParser\Node\Stmt\Enum_; use PhpParser\Node\Stmt\Expression; use PhpParser\Node\VariadicPlaceholder; use ReflectionClass; @@ -160,8 +165,13 @@ public function __construct( $generatedProperties[] = $interceptedProperty; } - // Proxy implements the same interfaces as the original class (no longer inherited) - $originalInterfaces = array_map(static fn(string $i) => '\\' . $i, $originalClass->getInterfaceNames()); + // Proxy implements the same interfaces as the original class (no longer inherited), the ones a partial + // reflection leaves out included + [$missingParentName, $missingInterfaceNames] = self::getMissingDeclaredAncestors($originalClass); + $originalInterfaces = array_map( + self::rootClassName(...), + [...$originalClass->getInterfaceNames(), ...$missingInterfaceNames], + ); $introducedInterfaces = array_merge($originalInterfaces, $introducedInterfaces); $introducedInterfaces[] = '\\' . Proxy::class; $introducedInterfaces = array_values(array_unique($introducedInterfaces)); @@ -185,7 +195,11 @@ public function __construct( // Proxy parent = original class parent (not the trait — there is no inheritance layer) $parentClass = $originalClass->getParentClass(); - $parentClassName = $parentClass !== false ? '\\' . $parentClass->getName() : null; + $parentClassName = match (true) { + $parentClass !== false => '\\' . $parentClass->getName(), + $missingParentName !== null => self::rootClassName($missingParentName), + default => null, + }; // Proxy modifiers: preserve final/abstract/readonly from original class. $modifiers = []; @@ -566,6 +580,52 @@ protected static function shortClassName(string $className): string return $lastSeparator === false ? $className : substr($className, $lastSeparator + 1); } + /** + * Parent class and interfaces declared by the original class whose source goaop/parser-reflection could not locate + * + * The weaver reflects classes partially (see AdviceMatcher::getAdvicesForClass()): a parent class or an interface + * declared in code generated at runtime, by a class_alias() or outside the Composer autoloader is left out of + * getParentClass() and getInterfaceNames(). The proxy still declares it under the name resolved from the source: + * the original class could not be loaded without it either. + * + * @return array{string|null, list} Name of the missing parent class (null if none), names of the + * missing interfaces + */ + protected static function getMissingDeclaredAncestors(ReflectionClass $originalClass): array + { + if (!$originalClass instanceof ParsedReflectionClass && !$originalClass instanceof ParsedReflectionEnum) { + return [null, []]; + } + $missingNames = $originalClass->getMissingClassNames(); + if ($missingNames === []) { + return [null, []]; + } + + $classNode = $originalClass->getNode(); + $parentName = $classNode instanceof Class_ && $classNode->extends !== null + ? self::resolvedName($classNode->extends) + : null; + $interfaceNames = $classNode instanceof Class_ || $classNode instanceof Enum_ + ? array_map(self::resolvedName(...), $classNode->implements) + : []; + + // Missing names include the ancestors missing for an available ancestor, which come with that one + return [ + in_array($parentName, $missingNames, true) ? $parentName : null, + array_values(array_intersect($interfaceNames, $missingNames)), + ]; + } + + /** + * Fully qualified name of a class referenced in the source + */ + private static function resolvedName(Name $name): string + { + $resolvedName = $name->getAttribute('resolvedName'); + + return $resolvedName instanceof FullyQualified ? $resolvedName->toString() : $name->toString(); + } + /** * Returns the class name rooted with a leading backslash, so that it is emitted fully qualified */ diff --git a/src/Proxy/EnumProxyGenerator.php b/src/Proxy/EnumProxyGenerator.php index 1fcb3c92..acdd6f59 100644 --- a/src/Proxy/EnumProxyGenerator.php +++ b/src/Proxy/EnumProxyGenerator.php @@ -124,8 +124,10 @@ public function __construct( // Built-in PHP enum interfaces (UnitEnum, BackedEnum) are excluded: PHP applies them // automatically when the `enum` keyword is used, and listing them explicitly in a // namespaced file would resolve them as e.g. Ns\UnitEnum instead of the global \UnitEnum. + // Interfaces left out of a partial reflection are declared too, see getMissingDeclaredAncestors() + [, $missingInterfaceNames] = self::getMissingDeclaredAncestors($originalClass); $originalInterfaces = array_filter( - $originalClass->getInterfaceNames(), + [...$originalClass->getInterfaceNames(), ...$missingInterfaceNames], static fn(string $i) => !in_array($i, self::BUILTIN_ENUM_INTERFACES, true), ); $originalInterfaces = array_map(static fn(string $i) => '\\' . $i, $originalInterfaces); diff --git a/tests/Aop/Exception/ExceptionMessagesTest.php b/tests/Aop/Exception/ExceptionMessagesTest.php index 22cd314c..ae6fc3c9 100644 --- a/tests/Aop/Exception/ExceptionMessagesTest.php +++ b/tests/Aop/Exception/ExceptionMessagesTest.php @@ -331,8 +331,8 @@ public static function namedConstructors(): array ), WeavingException::class, 'App\Transformer failed to transform /app/src/Admin/ReportController.php: Class ' - . 'GeneratedCode\Admin\BaseReportController was not found by locator. The weaver reads the parents, ' - . 'interfaces and traits of a class from their source files, which it finds through Composer: make ' + . 'GeneratedCode\Admin\BaseReportController was not found by locator. The weaver reads the classes ' + . 'a woven class depends on from their source files, which it finds through Composer: make ' . 'GeneratedCode\Admin\BaseReportController loadable by Composer (classmap, PSR-4 or ' . '$loader->addClassMap() before the aspect kernel is initialized), or exclude the classes that depend ' . 'on it from weaving with the excludePaths option.', @@ -346,8 +346,8 @@ public static function namedConstructors(): array )), ), WeavingException::class, - 'App\Transformer failed to transform /app/Foo.php: wrapped. The weaver reads the parents, ' - . 'interfaces and traits of a class from their source files, which it finds through Composer: make ' + 'App\Transformer failed to transform /app/Foo.php: wrapped. The weaver reads the classes ' + . 'a woven class depends on from their source files, which it finds through Composer: make ' . 'App\Aliased loadable by Composer (classmap, PSR-4 or $loader->addClassMap() before the aspect ' . 'kernel is initialized), or exclude the classes that depend on it from weaving with the ' . 'excludePaths option.', diff --git a/tests/Core/AdviceMatcherTest.php b/tests/Core/AdviceMatcherTest.php index f44880f5..3f4a3efc 100644 --- a/tests/Core/AdviceMatcherTest.php +++ b/tests/Core/AdviceMatcherTest.php @@ -18,6 +18,7 @@ use Go\Aop\Pointcut; use Go\Aop\Support\GenericPointcutAdvisor; use Go\ParserReflection\Locator\ComposerLocator; +use Go\ParserReflection\MissingAncestorPolicy; use Go\ParserReflection\ReflectionEngine; use Go\ParserReflection\ReflectionFile; use Go\ParserReflection\ReflectionFileNamespace; @@ -565,6 +566,37 @@ private function getInheritanceAdvices( return new AdviceMatcher($isWovenFile)->getAdvicesForClass(new ReflectionClass($className), ['advisor' => $advisor]); } + /** + * A class whose parent class and interface can't be located is matched with its own methods: the matcher switches + * the reflection to the partial policy before a pointcut walks the ancestors (goaop/parser-reflection#251) + */ + public function testClassWithUnlocatableAncestorsIsMatchedWithItsOwnMethods(): void + { + $previousPolicy = ReflectionEngine::getMissingAncestorPolicy(); + ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Strict); + try { + $class = new ReflectionFile(dirname(__DIR__) . '/Instrument/Transformer/_files/class-unknown-parent.php') + ->getFileNamespace('Test\ns1') + ->getClass('Test\ns1\RuleWithMissingParent'); + + // Walks the ancestors before the matcher touches any of its own state + $pointcut = $this->createMock(Pointcut::class); + $pointcut->method(PropertyHook::get('kind'))->willReturn(Pointcut::KIND_METHOD); + $pointcut->method('matches')->willReturnCallback( + static fn(ReflectionClass $class): bool => !$class->isSubclassOf(\Stringable::class), + ); + $advisor = new GenericPointcutAdvisor($pointcut, $this->createMock(Advice::class)); + + $advices = new AdviceMatcher()->getAdvicesForClass($class, ['advisor' => $advisor]); + + $this->assertSame(MissingAncestorPolicy::Partial, ReflectionEngine::getMissingAncestorPolicy()); + $this->assertTrue($class->isPartial()); + $this->assertSame(['getNodeType'], array_keys($advices[AspectContainer::METHOD_PREFIX] ?? [])); + } finally { + ReflectionEngine::setMissingAncestorPolicy($previousPolicy); + } + } + /** * Verifies that getAdvicesForFunctions() never matches an advisor without a function pointcut: * function interception needs no feature flag, the pointcut kind enables it. diff --git a/tests/Fixtures/project/src/Application/Issue251ReportController.php b/tests/Fixtures/project/src/Application/Issue251ReportController.php new file mode 100644 index 00000000..b7e8727e --- /dev/null +++ b/tests/Fixtures/project/src/Application/Issue251ReportController.php @@ -0,0 +1,27 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Go\Tests\TestProject\Application; + +use Go\Tests\TestProject\Generated\Issue251BaseController; +use Go\Tests\TestProject\Generated\Issue251Controller; + +/** + * Test fixture (goaop/parser-reflection#251): its parent class and interface are declared at runtime, Composer can't + * locate their source, so the weaver reflects the class partially + */ +class Issue251ReportController extends Issue251BaseController implements Issue251Controller +{ + public function report(): string + { + return 'report of ' . $this->handle(); + } +} diff --git a/tests/Fixtures/project/src/Aspect/Issue251Aspect.php b/tests/Fixtures/project/src/Aspect/Issue251Aspect.php new file mode 100644 index 00000000..3fc48c96 --- /dev/null +++ b/tests/Fixtures/project/src/Aspect/Issue251Aspect.php @@ -0,0 +1,36 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Go\Tests\TestProject\Aspect; + +use Go\Aop\Aspect; +use Go\Aop\Intercept\MethodInvocation; +use Go\Lang\Attribute as Pointcut; + +/** + * Records the advice executions on Issue251ReportController, whose ancestors can't be located + * (goaop/parser-reflection#251) + */ +class Issue251Aspect implements Aspect +{ + /** + * @var list + */ + public static array $calls = []; + + #[Pointcut\Around('execution(public Go\Tests\TestProject\Application\Issue251ReportController->*(*))')] + public function aroundControllerMethod(MethodInvocation $invocation): mixed + { + self::$calls[] = 'around:' . $invocation->getMethod()->name; + + return $invocation->proceed(); + } +} diff --git a/tests/Fixtures/project/src/Kernel/DefaultAspectKernel.php b/tests/Fixtures/project/src/Kernel/DefaultAspectKernel.php index 2e406582..4fa5cff9 100644 --- a/tests/Fixtures/project/src/Kernel/DefaultAspectKernel.php +++ b/tests/Fixtures/project/src/Kernel/DefaultAspectKernel.php @@ -15,6 +15,7 @@ use Go\Tests\TestProject\Aspect\EnumMethodAspect; use Go\Tests\TestProject\Aspect\GreetingAspect; use Go\Tests\TestProject\Aspect\InitializationAspect; +use Go\Tests\TestProject\Aspect\Issue251Aspect; use Go\Tests\TestProject\Aspect\Issue293Aspect; use Go\Tests\TestProject\Aspect\Issue781Aspect; use Go\Tests\TestProject\Aspect\LoggingAspect; @@ -40,6 +41,7 @@ protected function configureAop(AspectContainer $container): void $container->addLazyService(PromotedPropertyInterceptAspect::class, fn(): PromotedPropertyInterceptAspect => new PromotedPropertyInterceptAspect()); $container->addLazyService(Issue293Aspect::class, fn(): Issue293Aspect => new Issue293Aspect()); $container->addLazyService(Issue781Aspect::class, fn(): Issue781Aspect => new Issue781Aspect()); + $container->addLazyService(Issue251Aspect::class, fn(): Issue251Aspect => new Issue251Aspect()); $container->addLazyService(InitializationAspect::class, fn(): InitializationAspect => new InitializationAspect()); $container->addLazyService(WeavingAspect::class, fn(): WeavingAspect => new WeavingAspect()); $container->addLazyService(TraitCompositionAspect::class, fn(): TraitCompositionAspect => new TraitCompositionAspect()); diff --git a/tests/Functional/BaseFunctionalTestCase.php b/tests/Functional/BaseFunctionalTestCase.php index 5540250b..65879dc0 100644 --- a/tests/Functional/BaseFunctionalTestCase.php +++ b/tests/Functional/BaseFunctionalTestCase.php @@ -457,4 +457,36 @@ protected function assertClassStaticInitializationNotWoven( self::assertThat($identifier, $constraint, $message); } + + /** + * Runs the code in the fixture project, the code fills `$calls`, which is returned + * + * @return array + */ + protected function runAndRecordCalls(string $code): array + { + $phpExecutable = (new PhpExecutableFinder())->find(); + assert($phpExecutable !== false); + $script = sprintf( + 'include %s; $calls = []; %s echo json_encode($calls, JSON_THROW_ON_ERROR);', + var_export($this->configuration['frontController'], true), + $code, + ); + $process = new Process( + [$phpExecutable, '-r', $script], + null, + ['GO_AOP_CONFIGURATION' => $this->getConfigurationName()], + ); + $process->run(); + + $this->assertTrue( + $process->isSuccessful(), + 'Running the woven classes failed: ' . $process->getOutput() . $process->getErrorOutput(), + ); + $calls = json_decode(trim($process->getOutput()), true, flags: JSON_THROW_ON_ERROR); + $this->assertIsArray($calls); + + /** @var array $calls */ + return $calls; + } } diff --git a/tests/Functional/InheritedMethodWeavingTest.php b/tests/Functional/InheritedMethodWeavingTest.php index bdb39919..3ee14fe1 100644 --- a/tests/Functional/InheritedMethodWeavingTest.php +++ b/tests/Functional/InheritedMethodWeavingTest.php @@ -17,8 +17,6 @@ use Go\Tests\TestProject\Application\Issue781CardGateway; use Go\Tests\TestProject\Application\Issue781PlainRecord; use Go\Tests\TestProject\Application\Issue781RecordGateway; -use Symfony\Component\Process\PhpExecutableFinder; -use Symfony\Component\Process\Process; /** * An advice of an execution pointcut runs once per method execution, however many classes of the hierarchy are woven @@ -82,36 +80,4 @@ public function testInheritedMethodOfUnwovenParentIsInterceptedOnce(): void $this->assertSame(['record', ['around:describe']], $calls['record']); $this->assertSame(['record', ['around:describe']], $calls['archived']); } - - /** - * Runs the code in the fixture project, the code fills `$calls`, which is returned - * - * @return array - */ - private function runAndRecordCalls(string $code): array - { - $phpExecutable = (new PhpExecutableFinder())->find(); - assert($phpExecutable !== false); - $script = sprintf( - 'include %s; $calls = []; %s echo json_encode($calls, JSON_THROW_ON_ERROR);', - var_export($this->configuration['frontController'], true), - $code, - ); - $process = new Process( - [$phpExecutable, '-r', $script], - null, - ['GO_AOP_CONFIGURATION' => $this->getConfigurationName()], - ); - $process->run(); - - $this->assertTrue( - $process->isSuccessful(), - 'Running the woven classes failed: ' . $process->getOutput() . $process->getErrorOutput(), - ); - $calls = json_decode(trim($process->getOutput()), true, flags: JSON_THROW_ON_ERROR); - $this->assertIsArray($calls); - - /** @var array $calls */ - return $calls; - } } diff --git a/tests/Functional/PartialReflectionWeavingTest.php b/tests/Functional/PartialReflectionWeavingTest.php new file mode 100644 index 00000000..fe15d6bb --- /dev/null +++ b/tests/Functional/PartialReflectionWeavingTest.php @@ -0,0 +1,70 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Go\Functional; + +use Go\Tests\TestProject\Application\Issue251ReportController; + +/** + * A class whose ancestors can't be located is woven with its own methods instead of failing the file + * (goaop/parser-reflection#251) + */ +class PartialReflectionWeavingTest extends BaseFunctionalTestCase +{ + private const string AROUND = 'Go\\Tests\\TestProject\\Aspect\\Issue251Aspect->aroundControllerMethod'; + + /** + * Declares the parent class and the interface of Issue251ReportController the way generated code does: at + * runtime, without a source file Composer knows + */ + private const string DECLARE_ANCESTORS = <<<'PHP' + eval('namespace Go\Tests\TestProject\Generated; + interface Issue251Controller {} + abstract class Issue251BaseController { public function handle(): string { return "base"; } }'); + PHP; + + /** + * The cache was warmed up in a process where the ancestors don't exist: the own method is woven, the inherited + * one of the missing parent class is unknown to the weaver + */ + public function testOwnMethodsOfClassWithUnlocatableAncestorsAreWoven(): void + { + $this->assertMethodWoven(Issue251ReportController::class, 'report', self::AROUND); + $this->assertMethodNotWoven(Issue251ReportController::class, 'handle'); + } + + /** + * The proxy keeps the parent class and the interface declared by the original class + */ + public function testWovenClassKeepsItsUnlocatableAncestors(): void + { + $calls = $this->runAndRecordCalls(self::DECLARE_ANCESTORS . sprintf( + '$controller = new %1$s();' + . '$calls["report"] = [$controller->report(), %2$s::$calls];' + . '$calls["ancestors"] = [get_parent_class($controller), class_implements($controller)];', + '\\' . Issue251ReportController::class, + '\\Go\\Tests\\TestProject\\Aspect\\Issue251Aspect', + )); + + $this->assertSame(['report of base', ['around:report']], $calls['report']); + $this->assertSame( + [ + 'Go\\Tests\\TestProject\\Generated\\Issue251BaseController', + [ + 'Go\\Tests\\TestProject\\Generated\\Issue251Controller' => 'Go\\Tests\\TestProject\\Generated\\Issue251Controller', + 'Go\\Aop\\Proxy' => 'Go\\Aop\\Proxy', + ], + ], + $calls['ancestors'], + ); + } +} diff --git a/tests/Instrument/Transformer/WeavingTransformerTest.php b/tests/Instrument/Transformer/WeavingTransformerTest.php index 81b3022d..4efdff9e 100644 --- a/tests/Instrument/Transformer/WeavingTransformerTest.php +++ b/tests/Instrument/Transformer/WeavingTransformerTest.php @@ -21,6 +21,9 @@ use Go\Core\AspectKernel; use Go\Core\AspectLoader; use Go\Instrument\ClassLoading\CachePathManager; +use Go\ParserReflection\ClassNotFoundException; +use Go\ParserReflection\MissingAncestorPolicy; +use Go\ParserReflection\ReflectionEngine; use Go\VirtualFileSystem\FileSystem; use PHPUnit\Framework\MockObject\MockObject; use Go\Instrument\Transformer\Stubs\MultiLinePropertiesClass; @@ -236,6 +239,49 @@ public function testUnadvisedClassWithUnknownParentIsNotTransformed(): void $this->assertSame($source, $metadata->source); } + /** + * With the partial reflection the framework enables, a class whose parent class and interface can't be located is + * woven with its own methods, and its proxy still declares them (goaop/parser-reflection#251) + */ + public function testClassWithUnlocatableAncestorsIsWovenWithItsOwnMethods(): void + { + $metadata = $this->loadTestMetadata('class-unknown-parent'); + $result = $this->transformWithPolicy(MissingAncestorPolicy::Partial, $metadata); + + $this->assertSame(TransformerResult::Transformed, $result); + $this->assertStringContainsString('trait RuleWithMissingParentOriginalTrait', $metadata->source); + $this->assertSame(1, preg_match("/AOP_CACHE_DIR . '(.+)';$/m", $metadata->source, $matches)); + + $proxyContent = $this->normalizeWhitespaces((string) file_get_contents('vfs://' . $matches[1])); + $this->assertStringContainsString( + 'class RuleWithMissingParent extends \\Missing\\Optional\\Dependency\\BaseRule' + . ' implements \\Missing\\Optional\\Dependency\\Rule, \\Go\\Aop\\Proxy', + $proxyContent, + ); + $this->assertStringContainsString('public function getNodeType(): string', $proxyContent); + } + + /** + * Without the partial reflection, matching the methods of such a class fails on its missing parent class + */ + public function testClassWithUnlocatableAncestorsFailsWithStrictReflection(): void + { + $this->expectException(ClassNotFoundException::class); + + $this->transformWithPolicy(MissingAncestorPolicy::Strict, $this->loadTestMetadata('class-unknown-parent')); + } + + private function transformWithPolicy(MissingAncestorPolicy $policy, StreamMetaData $metadata): TransformerResult + { + $previousPolicy = ReflectionEngine::getMissingAncestorPolicy(); + ReflectionEngine::setMissingAncestorPolicy($policy); + try { + return $this->transformer->transform($metadata); + } finally { + ReflectionEngine::setMissingAncestorPolicy($previousPolicy); + } + } + /** * Aspects not loaded yet are loaded before matching: the AdvisorIndex usually loads them earlier, but a kernel * overriding registerTransformerServices() may run the weaver without the `new` rewriting rule diff --git a/tests/Instrument/Transformer/_files/enum-unknown-interface.php b/tests/Instrument/Transformer/_files/enum-unknown-interface.php new file mode 100644 index 00000000..8ac58191 --- /dev/null +++ b/tests/Instrument/Transformer/_files/enum-unknown-interface.php @@ -0,0 +1,20 @@ +value); + } + + public function jsonSerialize(): string + { + return $this->value; + } + } +} diff --git a/tests/Proxy/EnumProxyGeneratorTest.php b/tests/Proxy/EnumProxyGeneratorTest.php index 3bc20a5c..ae3505c1 100644 --- a/tests/Proxy/EnumProxyGeneratorTest.php +++ b/tests/Proxy/EnumProxyGeneratorTest.php @@ -14,6 +14,9 @@ use Go\Aop\Framework\BeforeInterceptor; use Go\Aop\Framework\GeneratedInterceptor; +use Go\ParserReflection\MissingAncestorPolicy; +use Go\ParserReflection\ReflectionEngine; +use Go\ParserReflection\ReflectionFile; use Go\Stubs\StubBackedEnum; use Go\Stubs\StubConstExprBackedEnum; use PHPUnit\Framework\TestCase; @@ -73,6 +76,32 @@ public function testGenerateProxyEnumMethod(): void $this->assertStringContainsString('__invoke($this', $output); } + /** + * An interface whose source can't be located is left out of the partial reflection the weaver uses, the proxy + * still declares it under its name from the source (goaop/parser-reflection#251) + */ + public function testProxyDeclaresInterfaceMissingFromPartialReflection(): void + { + $previousPolicy = ReflectionEngine::getMissingAncestorPolicy(); + ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Partial); + try { + $enum = new ReflectionFile(dirname(__DIR__) . '/Instrument/Transformer/_files/enum-unknown-interface.php') + ->getFileNamespace('Test\ns1') + ->getClass('Test\ns1\EnumWithMissingInterface'); + $this->assertSame(['Missing\Optional\Dependency\Labelled'], $enum->getMissingClassNames()); + + $classAdvices = ['method' => ['label' => [self::testAdvice('advisor.EnumWithMissingInterface->label')]]]; + $generator = new EnumProxyGenerator($enum, 'Test\ns1\EnumWithMissingInterfaceOriginalTrait', $classAdvices); + + $this->assertStringContainsString( + 'enum EnumWithMissingInterface : string implements \\JsonSerializable, \\Missing\\Optional\\Dependency\\Labelled, \\Go\\Aop\\Proxy', + $generator->generate(), + ); + } finally { + ReflectionEngine::setMissingAncestorPolicy($previousPolicy); + } + } + /** * A proxy for an intercepted static method on an enum must dispatch via static::class. */ From 85ead86160d1f9297b0ad7565fd3fc83a5634cd7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 22:06:47 +0000 Subject: [PATCH 2/4] fix(proxy): declare the type of the reflection of getMissingDeclaredAncestors() PHPStan requires the type parameter of the generic native ReflectionClass, as the other methods of ClassProxyGenerator declare it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FxhC1CBg4rnTu9UjAMcCpL --- src/Proxy/ClassProxyGenerator.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Proxy/ClassProxyGenerator.php b/src/Proxy/ClassProxyGenerator.php index 96574721..2c26b6b7 100644 --- a/src/Proxy/ClassProxyGenerator.php +++ b/src/Proxy/ClassProxyGenerator.php @@ -588,6 +588,8 @@ protected static function shortClassName(string $className): string * getParentClass() and getInterfaceNames(). The proxy still declares it under the name resolved from the source: * the original class could not be loaded without it either. * + * @param ReflectionClass $originalClass + * * @return array{string|null, list} Name of the missing parent class (null if none), names of the * missing interfaces */ From 2b6f7cf187910749cf75008685d0e900ba38ebe8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 22:14:06 +0000 Subject: [PATCH 3/4] feat(kernel): make partial reflection an opt-in Features::PARTIAL_REFLECTION flag Partial reflection was switched on unconditionally by AdviceMatcher::getAdvicesForClass(), so applications had no say. It is now the Features::PARTIAL_REFLECTION flag (256: 1, 2 and 128 belonged to removed flags), applied by AspectKernel::init(). Without the flag the kernel leaves the policy of goaop/parser-reflection as it is (strict by default), so a class whose ancestors can't be located fails to weave as before; the weaving error hint now names the flag. The functional fixture moves to its own directory, woven by the new partial_reflection configuration only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FxhC1CBg4rnTu9UjAMcCpL --- CHANGELOG.md | 2 +- composer.json | 3 +- docs/configuration.md | 1 + src/Aop/Exception/WeavingException.php | 25 ++++++++++++-- src/Aop/Features.php | 14 +++++++- src/Core/AGENTS.md | 4 +-- src/Core/AdviceMatcher.php | 6 ---- src/Core/AspectKernel.php | 16 +++++++++ src/Instrument/AGENTS.md | 12 +++---- src/Proxy/ClassProxyGenerator.php | 4 +-- tests/Aop/Exception/ExceptionMessagesTest.php | 16 +++++++++ tests/Core/AdviceMatcherTest.php | 8 ++--- tests/Core/AspectKernelTest.php | 33 +++++++++++++++++++ .../Issue251ReportController.php | 5 +-- .../project/src/Aspect/Issue251Aspect.php | 2 +- tests/Fixtures/project/web/configuration.php | 15 +++++++++ .../PartialReflectionWeavingTest.php | 11 +++++-- .../Transformer/WeavingTransformerTest.php | 4 +-- 18 files changed, 146 insertions(+), 35 deletions(-) rename tests/Fixtures/project/{src/Application => partial}/Issue251ReportController.php (76%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1162e514..ac4607a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,7 +27,7 @@ See [UPGRADE-4.0.md](UPGRADE-4.0.md) for the migration guide. * [Feature] **Cache warm-up into another directory** — `new CacheWarmer($kernel, cacheDir: $dir)` and `cache:warmup:aop --cache-dir=DIR` (also with `--workers`) build the cache in a directory other than the one of the kernel, from scratch, while the kernel keeps serving the process from its own directory (`CachePathManager::withCacheDir()`): a deployment prepares the cache of the next release next to the running one, the way Symfony's `cache:clear` warms a new cache directory up before swapping it in. Woven sources served while such a build runs include their proxies from the directory being built. * [Feature] [BC BREAK] **Doctrine bridge rewritten for the trait-based engine (#671)** — new `Go\Bridge\Doctrine\WovenEntityClassLocator` lets Doctrine mapping drivers (ORM 3.6+) discover entities through the autoloader, so the woven class is mapped instead of the original source, and entities loaded before discovery are no longer missed. `MetadataLoadInterceptor` no longer rewrites metadata (the old mapped-superclass workaround only matched the extend-based engine); it now reports woven entities with intercepted mapped properties when Doctrine native lazy objects are disabled. It is registered as a plain listener: `$eventManager->addEventListener(Events::loadClassMetadata, new MetadataLoadInterceptor())` (it is no longer an `EventSubscriber`). * [Feature] **Aspects whose creation runs their own advices are reported** — the container marks a deferred service while its factory runs, and an interceptor about to run an advice of an aspect being created throws the new `Go\Aop\Exception\AspectCircularReferenceException` (a `RuntimeException` implementing PSR `ContainerExceptionInterface`) with the aspect, the joinpoint and the calls from the creation to the advice, e.g. `ClockAspect -> Scheduler->__construct() -> Clock->now() -> ClockAspect->beforeNow()`. Such an advice used to run on the half-initialized lazy aspect: PHP reported an uninitialized property at best, an advice reading no property ran without any error (#783). -* [Feature] **Classes with ancestors Composer can not locate are woven** — the weaver reflects classes with the partial policy of goaop/parser-reflection 4.1/5.1 (`MissingAncestorPolicy::Partial`): a parent class, interface or trait declared by code generated at runtime, by a `class_alias()` or in a file outside the Composer autoloader no longer fails the file (and `cache:warmup:aop`). The class is matched and woven with its own methods and properties and the ones of its available ancestors; members inherited from a missing ancestor are not intercepted. The proxy still declares the missing parent class and interfaces, which must be loaded by the time the class is. The policy is switched on by `AdviceMatcher::getAdvicesForClass()`, so requests served from the cache never reflect. +* [Feature] **Weaving classes whose ancestors Composer can not locate** — the new `Features::PARTIAL_REFLECTION` flag reflects classes with the partial policy of goaop/parser-reflection 4.1/5.1 (`MissingAncestorPolicy::Partial`, applied by `AspectKernel::init()`): a parent class, interface or trait declared by code generated at runtime, by a `class_alias()` or in a file outside the Composer autoloader no longer fails the file (and `cache:warmup:aop`). The class is matched and woven with its own methods and properties and the ones of its available ancestors; members inherited from a missing ancestor are not intercepted. The proxy still declares the missing parent class and interfaces, which must be loaded by the time the class is. Without the flag such a class fails to weave, as before. * [Feature] **Hint for classes Composer can not locate** — when weaving fails because goaop/parser-reflection can not find the source of a parent class, interface or trait (code generated at runtime, a `class_alias()`, a file outside the Composer autoloader), the `WeavingException` tells how to make the class loadable or to exclude the classes depending on it with `excludePaths` (#782). **Changed** diff --git a/composer.json b/composer.json index 19943548..e60b9e0e 100644 --- a/composer.json +++ b/composer.json @@ -65,7 +65,8 @@ "psr-4": { "Demo\\": "demos/Demo/", "Go\\": "tests/", - "Go\\Tests\\TestProject\\": "tests/Fixtures/project/src/" + "Go\\Tests\\TestProject\\": "tests/Fixtures/project/src/", + "Go\\Tests\\TestProject\\Partial\\": "tests/Fixtures/project/partial/" }, "files": [ "tests/functions.php", diff --git a/docs/configuration.md b/docs/configuration.md index 54d4463d..92734f07 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -35,6 +35,7 @@ Combine the flags with `|`, e.g. `'features' => Features::INTERCEPT_INCLUDES | F |-----------------------------|--------| | `INTERCEPT_INCLUDES` | Routes `include`/`require` in woven files through the weaver, for legacy code that is not loaded by Composer. | | `PREBUILT_CACHE` | Trusts the cache built at deploy time completely. Skips the cache directory and writability probes, source `filemtime` comparisons, tracked-resource checks and advisor cache freshness checks, and never writes to the cache directory. Rebuilding the cache on every deploy is your responsibility. Works on read-only file systems. | +| `PARTIAL_REFLECTION` | Weaves a class whose parent class, interface or trait can not be located: declared by code generated at runtime, by a `class_alias()` or in a file outside the Composer autoloader. The class is matched and woven with its own methods and properties and the ones of its available ancestors; members inherited from a missing ancestor are not intercepted. Without the flag such a class fails to weave. | Function and initialization pointcuts need no flag: the framework enables their machinery from the registered aspects, lazily registered ones included. An `execution(Namespace\function(*))` pointcut weaves function proxies into diff --git a/src/Aop/Exception/WeavingException.php b/src/Aop/Exception/WeavingException.php index 9a62ffeb..81e040b7 100644 --- a/src/Aop/Exception/WeavingException.php +++ b/src/Aop/Exception/WeavingException.php @@ -12,6 +12,7 @@ namespace Go\Aop\Exception; +use Go\ParserReflection\ClassNotFoundException; use RuntimeException; use Throwable; @@ -58,6 +59,10 @@ public static function transformerFailed(string $transformerClass, string $uri, rtrim($message, '.'), $missing, ); + if (self::hasClassNotFoundByLocator($previous)) { + $message .= ' With the Features::PARTIAL_REFLECTION flag, a class whose parent class, interface or ' + . 'trait can not be located is woven with its own members.'; + } } return new self($message, previous: $previous); @@ -197,9 +202,9 @@ public static function functionReturnsByReference(string $functionName): self * Name of the class that goaop/parser-reflection could not find the source of, found in the exception chain * * A class declared by code generated at runtime, by a class_alias() or in a file Composer does not know can not be - * reflected from the source files. A missing ancestor is left out of the partial reflection the weaver uses, but - * a file that does not declare the class it was located for, or a class used in a constant expression, still - * fails. + * reflected from the source files. With Features::PARTIAL_REFLECTION a missing ancestor is left out of the + * reflection instead, but a file that does not declare the class it was located for, or a class used in a constant + * expression, still fails. */ private static function unlocatableClass(Throwable $exception): ?string { @@ -211,4 +216,18 @@ private static function unlocatableClass(Throwable $exception): ?string return null; } + + /** + * Tells whether goaop/parser-reflection failed in the exception chain because its locator found no source file + */ + private static function hasClassNotFoundByLocator(Throwable $exception): bool + { + for ($cause = $exception; $cause !== null; $cause = $cause->getPrevious()) { + if ($cause instanceof ClassNotFoundException) { + return true; + } + } + + return false; + } } diff --git a/src/Aop/Features.php b/src/Aop/Features.php index 153567f9..c8c7aff7 100644 --- a/src/Aop/Features.php +++ b/src/Aop/Features.php @@ -37,11 +37,23 @@ final class Features */ public const int PREBUILT_CACHE = 64; + /** + * Weaves a class whose parent class, interface or trait can not be located + * + * goaop/parser-reflection reads the ancestors of a class from their source files, found through Composer. An + * ancestor declared by code generated at runtime, by a `class_alias()` or in a file outside the Composer + * autoloader fails the class by default (strict). With this flag the class is reflected partially: it is matched + * and woven with its own members and the ones of its available ancestors, members inherited from a missing + * ancestor are not intercepted. The proxy still declares the missing parent class and interfaces. + */ + public const int PARTIAL_REFLECTION = 256; + /** * Mask of every defined feature flag */ public const int ALL = self::INTERCEPT_INCLUDES - | self::PREBUILT_CACHE; + | self::PREBUILT_CACHE + | self::PARTIAL_REFLECTION; /** * Holder of constants, never instantiated diff --git a/src/Core/AGENTS.md b/src/Core/AGENTS.md index d5a0281f..87b62e4d 100644 --- a/src/Core/AGENTS.md +++ b/src/Core/AGENTS.md @@ -22,8 +22,8 @@ - Lives in the nested Go\Core\Cache namespace (CachedAspectLoader, AdvisorCacheCompiler, AdvisorCachePrinter, CacheFileWriter — all @internal); format, naming and error-handling rules: see src/Core/Cache/AGENTS.md - AttributeAspectLoaderExtension — handles PHP 8 attribute-based aspect definitions; throws AspectException for non-public advice methods (first-class callable advices require public visibility; #[Pointcut]-only methods exempt) - AdviceMatcher — given class reflector, returns applicable advisors keyed by join point - - getAdvicesForClass() first switches goaop/parser-reflection to `MissingAncestorPolicy::Partial`: ancestors that can't be - located are left out instead of failing the class (src/Instrument/AGENTS.md § Partial reflection) + - With Features::PARTIAL_REFLECTION it matches classes whose ancestors can't be located with their own members and the + ones of the available ancestors (src/Instrument/AGENTS.md § Partial reflection) - Scans IS_PUBLIC|IS_PROTECTED|IS_PRIVATE methods - Private methods from parent classes excluded - Inherited methods (`$method->class` is a parent; trait methods name the class itself): skipped per advisor when an diff --git a/src/Core/AdviceMatcher.php b/src/Core/AdviceMatcher.php index d6a40f58..a698a4ac 100644 --- a/src/Core/AdviceMatcher.php +++ b/src/Core/AdviceMatcher.php @@ -19,8 +19,6 @@ use Go\Aop\Pointcut; use Go\Aop\Proxy; use Go\Instrument\PathResolver; -use Go\ParserReflection\MissingAncestorPolicy; -use Go\ParserReflection\ReflectionEngine; use Go\ParserReflection\ReflectionFileNamespace; use ReflectionClass; use ReflectionFunction; @@ -100,10 +98,6 @@ public function getAdvicesForFunctions(ReflectionFileNamespace $namespace, array */ public function getAdvicesForClass(ReflectionClass $class, array $advisors): array { - // Classes are matched, then woven, with partial reflection: an ancestor declared in code generated at runtime, - // by a class_alias() or outside the Composer autoloader is left out instead of failing the class. Switched on - // here, before any pointcut walks the ancestors, so that requests served from the cache never pay for it - ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Partial); $classAdvices = []; foreach ($advisors as $advisorId => $advisor) { diff --git a/src/Core/AspectKernel.php b/src/Core/AspectKernel.php index 6bd6ee0c..a3b19de1 100644 --- a/src/Core/AspectKernel.php +++ b/src/Core/AspectKernel.php @@ -25,6 +25,8 @@ use Go\Instrument\Transformer\FilterInjectorTransformer; use Go\Instrument\Transformer\MagicConstantTransformer; use Go\Instrument\Transformer\WeavingTransformer; +use Go\ParserReflection\MissingAncestorPolicy; +use Go\ParserReflection\ReflectionEngine; use ReflectionClass; /** @@ -136,6 +138,7 @@ public function init(array $options = []): void } $this->options = $this->normalizeOptions($options); + $this->configureReflection(); if (!defined('AOP_ROOT_DIR')) { define('AOP_ROOT_DIR', $this->options['appDir']); } @@ -196,6 +199,19 @@ public function init(array $options = []): void $this->wasInitialized = true; } + /** + * Applies the reflection features to goaop/parser-reflection, which the weaver reflects the sources with + * + * Without Features::PARTIAL_REFLECTION the policy of the engine stays as it is (strict by default): a class whose + * parent class, interface or trait can not be located fails to weave. + */ + private function configureReflection(): void + { + if ($this->hasFeature(Features::PARTIAL_REFLECTION)) { + ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Partial); + } + } + /** * Tells whether the kernel of the process exists and was initialized * diff --git a/src/Instrument/AGENTS.md b/src/Instrument/AGENTS.md index 3c6f45ce..b40d525d 100644 --- a/src/Instrument/AGENTS.md +++ b/src/Instrument/AGENTS.md @@ -114,12 +114,12 @@ Classes implementing \Go\Aop\Aspect: unconditionally skipped by WeavingTransform The check (`implementsInterface(Aspect::class)`) runs in WeavingTransformer::weaveClass() only AFTER advices were found: it reflects (and parses) every ancestor, so unadvised classes must never pay for it (#748). -## Partial reflection: ancestors that can't be located -AdviceMatcher::getAdvicesForClass() sets `ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Partial)` -(goaop/parser-reflection 4.1/5.1) as its first statement: a parent class, interface or trait whose source the locator -can't find (generated at runtime, `class_alias()`, outside the Composer autoloader) is left out of the reflection instead -of failing the class. Not in AspectKernel::init() (cache hits never reflect), not in the AdviceMatcher service factory (a -native lazy proxy initializes on the first property access, after `$pointcut->matches()` may have walked the ancestors). +## Partial reflection: ancestors that can't be located (Features::PARTIAL_REFLECTION) +Opt-in. AspectKernel::init() → configureReflection() sets +`ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Partial)` (goaop/parser-reflection 4.1/5.1) when the +flag is on, and leaves the engine alone otherwise (strict: a missing ancestor fails the class, WeavingException hint +#782). With the flag, a parent class, interface or trait whose source the locator can't find (generated at runtime, +`class_alias()`, outside the Composer autoloader) is left out of the reflection instead of failing the class. Consequences: - Matching sees the class's own members and the ones of its available ancestors; members inherited from a missing ancestor are never matched, so never intercepted. diff --git a/src/Proxy/ClassProxyGenerator.php b/src/Proxy/ClassProxyGenerator.php index 2c26b6b7..8410d892 100644 --- a/src/Proxy/ClassProxyGenerator.php +++ b/src/Proxy/ClassProxyGenerator.php @@ -583,8 +583,8 @@ protected static function shortClassName(string $className): string /** * Parent class and interfaces declared by the original class whose source goaop/parser-reflection could not locate * - * The weaver reflects classes partially (see AdviceMatcher::getAdvicesForClass()): a parent class or an interface - * declared in code generated at runtime, by a class_alias() or outside the Composer autoloader is left out of + * With Features::PARTIAL_REFLECTION the weaver reflects classes partially: a parent class or an interface declared + * in code generated at runtime, by a class_alias() or outside the Composer autoloader is left out of * getParentClass() and getInterfaceNames(). The proxy still declares it under the name resolved from the source: * the original class could not be loaded without it either. * diff --git a/tests/Aop/Exception/ExceptionMessagesTest.php b/tests/Aop/Exception/ExceptionMessagesTest.php index ae6fc3c9..3c2e8e06 100644 --- a/tests/Aop/Exception/ExceptionMessagesTest.php +++ b/tests/Aop/Exception/ExceptionMessagesTest.php @@ -17,6 +17,7 @@ use Dissect\Parser\Exception\UnexpectedTokenException; use Go\Aop\Framework\TraitIntroductionInfo; use Go\Core\AspectContainer; +use Go\ParserReflection\ClassNotFoundException; use InvalidArgumentException; use LogicException; use PHPUnit\Framework\Attributes\DataProvider; @@ -337,6 +338,21 @@ public static function namedConstructors(): array . '$loader->addClassMap() before the aspect kernel is initialized), or exclude the classes that depend ' . 'on it from weaving with the excludePaths option.', ], + 'transformer failed, ancestor not found by locator' => [ + static fn() => WeavingException::transformerFailed( + 'App\Transformer', + '/app/src/Admin/ReportController.php', + new ClassNotFoundException('GeneratedCode\Admin\BaseReportController'), + ), + WeavingException::class, + 'App\Transformer failed to transform /app/src/Admin/ReportController.php: Class ' + . 'GeneratedCode\Admin\BaseReportController was not found by locator. The weaver reads the classes ' + . 'a woven class depends on from their source files, which it finds through Composer: make ' + . 'GeneratedCode\Admin\BaseReportController loadable by Composer (classmap, PSR-4 or ' + . '$loader->addClassMap() before the aspect kernel is initialized), or exclude the classes that depend ' + . 'on it from weaving with the excludePaths option. With the Features::PARTIAL_REFLECTION flag, a class ' + . 'whose parent class, interface or trait can not be located is woven with its own members.', + ], 'transformer failed, class not found in the file' => [ static fn() => WeavingException::transformerFailed( 'App\Transformer', diff --git a/tests/Core/AdviceMatcherTest.php b/tests/Core/AdviceMatcherTest.php index 3f4a3efc..77d6fb11 100644 --- a/tests/Core/AdviceMatcherTest.php +++ b/tests/Core/AdviceMatcherTest.php @@ -567,19 +567,18 @@ private function getInheritanceAdvices( } /** - * A class whose parent class and interface can't be located is matched with its own methods: the matcher switches - * the reflection to the partial policy before a pointcut walks the ancestors (goaop/parser-reflection#251) + * With the partial reflection of Features::PARTIAL_REFLECTION, a class whose parent class and interface can't be + * located is matched with its own methods, also by a pointcut walking its ancestors (goaop/parser-reflection#251) */ public function testClassWithUnlocatableAncestorsIsMatchedWithItsOwnMethods(): void { $previousPolicy = ReflectionEngine::getMissingAncestorPolicy(); - ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Strict); + ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Partial); try { $class = new ReflectionFile(dirname(__DIR__) . '/Instrument/Transformer/_files/class-unknown-parent.php') ->getFileNamespace('Test\ns1') ->getClass('Test\ns1\RuleWithMissingParent'); - // Walks the ancestors before the matcher touches any of its own state $pointcut = $this->createMock(Pointcut::class); $pointcut->method(PropertyHook::get('kind'))->willReturn(Pointcut::KIND_METHOD); $pointcut->method('matches')->willReturnCallback( @@ -589,7 +588,6 @@ public function testClassWithUnlocatableAncestorsIsMatchedWithItsOwnMethods(): v $advices = new AdviceMatcher()->getAdvicesForClass($class, ['advisor' => $advisor]); - $this->assertSame(MissingAncestorPolicy::Partial, ReflectionEngine::getMissingAncestorPolicy()); $this->assertTrue($class->isPartial()); $this->assertSame(['getNodeType'], array_keys($advices[AspectContainer::METHOD_PREFIX] ?? [])); } finally { diff --git a/tests/Core/AspectKernelTest.php b/tests/Core/AspectKernelTest.php index 14498d0a..7f533d72 100644 --- a/tests/Core/AspectKernelTest.php +++ b/tests/Core/AspectKernelTest.php @@ -23,6 +23,8 @@ use Go\Instrument\Transformer\SyntaxTreeRewriter; use Go\Instrument\Transformer\TransformerResult; use Go\Instrument\Transformer\WeavingTransformer; +use Go\ParserReflection\MissingAncestorPolicy; +use Go\ParserReflection\ReflectionEngine; use PhpParser\Node; use PhpParser\Node\Scalar\String_; use PHPUnit\Framework\Attributes\DataProvider; @@ -232,6 +234,37 @@ public function testHasFeatureRejectsUnknownFeature(int $feature): void $kernel->hasFeature($feature); } + /** + * Features::PARTIAL_REFLECTION switches goaop/parser-reflection to the partial policy, without it the kernel leaves + * the policy of the engine as it is (goaop/parser-reflection#251) + */ + #[DataProvider('reflectionFeatures')] + public function testInitConfiguresMissingAncestorPolicy(int $features, MissingAncestorPolicy $expectedPolicy): void + { + $previousPolicy = ReflectionEngine::getMissingAncestorPolicy(); + ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Strict); + try { + $kernel = $this->makeKernel(); + $this->setKernelOptions($kernel, ['features' => $features]); + + new ReflectionMethod($kernel, 'configureReflection')->invoke($kernel); + + $this->assertSame($expectedPolicy, ReflectionEngine::getMissingAncestorPolicy()); + } finally { + ReflectionEngine::setMissingAncestorPolicy($previousPolicy); + } + } + + /** + * @return iterable + */ + public static function reflectionFeatures(): iterable + { + yield 'partial reflection' => [Features::PARTIAL_REFLECTION, MissingAncestorPolicy::Partial]; + yield 'with other features' => [Features::PARTIAL_REFLECTION | Features::PREBUILT_CACHE, MissingAncestorPolicy::Partial]; + yield 'not enabled' => [Features::INTERCEPT_INCLUDES, MissingAncestorPolicy::Strict]; + } + public function testGetOptionsReturnsCurrentlyStoredOptions(): void { $kernel = $this->makeKernel(); diff --git a/tests/Fixtures/project/src/Application/Issue251ReportController.php b/tests/Fixtures/project/partial/Issue251ReportController.php similarity index 76% rename from tests/Fixtures/project/src/Application/Issue251ReportController.php rename to tests/Fixtures/project/partial/Issue251ReportController.php index b7e8727e..c2139272 100644 --- a/tests/Fixtures/project/src/Application/Issue251ReportController.php +++ b/tests/Fixtures/project/partial/Issue251ReportController.php @@ -9,14 +9,15 @@ * with this source code in the file LICENSE. */ -namespace Go\Tests\TestProject\Application; +namespace Go\Tests\TestProject\Partial; use Go\Tests\TestProject\Generated\Issue251BaseController; use Go\Tests\TestProject\Generated\Issue251Controller; /** * Test fixture (goaop/parser-reflection#251): its parent class and interface are declared at runtime, Composer can't - * locate their source, so the weaver reflects the class partially + * locate their source. Only the 'partial_reflection' configuration weaves this directory, with + * Features::PARTIAL_REFLECTION: without the flag the class fails to weave */ class Issue251ReportController extends Issue251BaseController implements Issue251Controller { diff --git a/tests/Fixtures/project/src/Aspect/Issue251Aspect.php b/tests/Fixtures/project/src/Aspect/Issue251Aspect.php index 3fc48c96..f57fd742 100644 --- a/tests/Fixtures/project/src/Aspect/Issue251Aspect.php +++ b/tests/Fixtures/project/src/Aspect/Issue251Aspect.php @@ -26,7 +26,7 @@ class Issue251Aspect implements Aspect */ public static array $calls = []; - #[Pointcut\Around('execution(public Go\Tests\TestProject\Application\Issue251ReportController->*(*))')] + #[Pointcut\Around('execution(public Go\Tests\TestProject\Partial\Issue251ReportController->*(*))')] public function aroundControllerMethod(MethodInvocation $invocation): mixed { self::$calls[] = 'around:' . $invocation->getMethod()->name; diff --git a/tests/Fixtures/project/web/configuration.php b/tests/Fixtures/project/web/configuration.php index 49d5d131..d2be8b33 100644 --- a/tests/Fixtures/project/web/configuration.php +++ b/tests/Fixtures/project/web/configuration.php @@ -69,6 +69,21 @@ ], ], + // Weaves a directory with a class whose ancestors can't be located (goaop/parser-reflection#251) + 'partial_reflection' => [ + 'kernel' => \Go\Tests\TestProject\Kernel\DefaultAspectKernel::class, + 'console' => __DIR__ . '/../bin/console', + 'frontController' => __DIR__ . '/../web/index.php', + 'appDir' => __DIR__ . '/../', + 'debug' => true, + 'cacheDir' => __DIR__ . '/../var/cache/aspect', + 'features' => \Go\Aop\Features::PARTIAL_REFLECTION, + 'includePaths' => [ + __DIR__ . '/../src/', + __DIR__ . '/../partial/', + ], + ], + 'inconsistent_weaving' => [ 'kernel' => \Go\Tests\TestProject\Kernel\InconsistentlyWeavingAspectKernel::class, 'console' => __DIR__ . '/../bin/console', diff --git a/tests/Functional/PartialReflectionWeavingTest.php b/tests/Functional/PartialReflectionWeavingTest.php index fe15d6bb..be926280 100644 --- a/tests/Functional/PartialReflectionWeavingTest.php +++ b/tests/Functional/PartialReflectionWeavingTest.php @@ -12,11 +12,11 @@ namespace Go\Functional; -use Go\Tests\TestProject\Application\Issue251ReportController; +use Go\Tests\TestProject\Partial\Issue251ReportController; /** - * A class whose ancestors can't be located is woven with its own methods instead of failing the file - * (goaop/parser-reflection#251) + * With Features::PARTIAL_REFLECTION, a class whose ancestors can't be located is woven with its own methods instead + * of failing the file (goaop/parser-reflection#251) */ class PartialReflectionWeavingTest extends BaseFunctionalTestCase { @@ -32,6 +32,11 @@ interface Issue251Controller {} abstract class Issue251BaseController { public function handle(): string { return "base"; } }'); PHP; + protected function getConfigurationName(): string + { + return 'partial_reflection'; + } + /** * The cache was warmed up in a process where the ancestors don't exist: the own method is woven, the inherited * one of the missing parent class is unknown to the weaver diff --git a/tests/Instrument/Transformer/WeavingTransformerTest.php b/tests/Instrument/Transformer/WeavingTransformerTest.php index 4efdff9e..9839dab8 100644 --- a/tests/Instrument/Transformer/WeavingTransformerTest.php +++ b/tests/Instrument/Transformer/WeavingTransformerTest.php @@ -240,8 +240,8 @@ public function testUnadvisedClassWithUnknownParentIsNotTransformed(): void } /** - * With the partial reflection the framework enables, a class whose parent class and interface can't be located is - * woven with its own methods, and its proxy still declares them (goaop/parser-reflection#251) + * With the partial reflection of Features::PARTIAL_REFLECTION, a class whose parent class and interface can't be + * located is woven with its own methods, and its proxy still declares them (goaop/parser-reflection#251) */ public function testClassWithUnlocatableAncestorsIsWovenWithItsOwnMethods(): void { From 918387a2413555b7f8fe939f4dd014bc2d43fcb2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 09:33:22 +0000 Subject: [PATCH 4/4] refactor(proxy): name missing ancestors through parser-reflection 4.2/5.2 Review feedback: reading the class node to recover the parent class and interfaces that a partial reflection could not locate did the work of goaop/parser-reflection. 4.2.0/5.2.0 names them itself: getParentClassName() returns the parent as written in the source, located or not, and getInterfaceNames() of a partial reflection includes the missing interfaces. ClassProxyGenerator::getMissingDeclaredAncestors() and its node code are removed: the class proxy takes its parent from getParentClassName(), the class and enum proxies their interfaces from getInterfaceNames() as before. Requires goaop/parser-reflection ^4.2.0 || ^5.2.0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FxhC1CBg4rnTu9UjAMcCpL --- CHANGELOG.md | 4 +- composer.json | 2 +- src/Instrument/AGENTS.md | 10 ++-- src/Proxy/ClassProxyGenerator.php | 78 +++++-------------------------- src/Proxy/EnumProxyGenerator.php | 4 +- 5 files changed, 22 insertions(+), 76 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d3f862f4..8b417381 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ See [UPGRADE-4.0.md](UPGRADE-4.0.md) for the migration guide. **Requirements** * [BC BREAK] Requires PHP 8.4+ -* [BC BREAK] **Dependencies** — `ext-tokenizer`, `goaop/parser-reflection` ^4.1.0 || ^5.1.0, `goaop/dissect` ^4.0, `psr/container` ^1.1 || ^2.0 and `symfony/finder` ^7.4 || ^8.0. `nikic/php-parser` 5 comes through parser-reflection and is no longer required directly. `symfony/console` ^7.4 || ^8.0 is needed for the `bin/aspect` tool. +* [BC BREAK] **Dependencies** — `ext-tokenizer`, `goaop/parser-reflection` ^4.2.0 || ^5.2.0, `goaop/dissect` ^4.0, `psr/container` ^1.1 || ^2.0 and `symfony/finder` ^7.4 || ^8.0. `nikic/php-parser` 5 comes through parser-reflection and is no longer required directly. `symfony/console` ^7.4 || ^8.0 is needed for the `bin/aspect` tool. **Added** * [Feature] **First-class callable advices** — the main way advices are now wired into woven code. Generated proxies declare each aspect-method advice as `Interceptor::before(The::aspect(MonitorAspect::class)->beforeMethodExecution(...))` — an eager first-class callable, since the interceptor list is only built while the intercepted method or hook is already executing (`LazyAdvisorAccessor` is removed). Compiled advisor cache files use the same facade in its lazy static-data form, e.g. `Interceptor::before(MonitorAspect::class, 'beforeMethodExecution')`, which returns a native PHP lazy proxy: interceptor construction, aspect resolution from the container and advice callable creation are all deferred until the advice is actually used, so cached advices whose pointcut never matches never instantiate their aspect. Advices registered in the container as plain closures (not aspect methods) are resolved through the new `The::advice('advisorId')` accessor, which unwraps `Advisor` and interceptor values down to the raw advice closure. @@ -27,7 +27,7 @@ See [UPGRADE-4.0.md](UPGRADE-4.0.md) for the migration guide. * [Feature] **Cache warm-up into another directory** — `new CacheWarmer($kernel, cacheDir: $dir)` and `cache:warmup:aop --cache-dir=DIR` (also with `--workers`) build the cache in a directory other than the one of the kernel, from scratch, while the kernel keeps serving the process from its own directory (`CachePathManager::withCacheDir()`): a deployment prepares the cache of the next release next to the running one, the way Symfony's `cache:clear` warms a new cache directory up before swapping it in. Woven sources served while such a build runs include their proxies from the directory being built. * [Feature] [BC BREAK] **Doctrine bridge rewritten for the trait-based engine (#671)** — new `Go\Bridge\Doctrine\WovenEntityClassLocator` lets Doctrine mapping drivers (ORM 3.6+) discover entities through the autoloader, so the woven class is mapped instead of the original source, and entities loaded before discovery are no longer missed. `MetadataLoadInterceptor` no longer rewrites metadata (the old mapped-superclass workaround only matched the extend-based engine); it now reports woven entities with intercepted mapped properties when Doctrine native lazy objects are disabled. It is registered as a plain listener: `$eventManager->addEventListener(Events::loadClassMetadata, new MetadataLoadInterceptor())` (it is no longer an `EventSubscriber`). * [Feature] **Aspects whose creation runs their own advices are reported** — the container marks a deferred service while its factory runs, and an interceptor about to run an advice of an aspect being created throws the new `Go\Aop\Exception\AspectCircularReferenceException` (a `RuntimeException` implementing PSR `ContainerExceptionInterface`) with the aspect, the joinpoint and the calls from the creation to the advice, e.g. `ClockAspect -> Scheduler->__construct() -> Clock->now() -> ClockAspect->beforeNow()`. Such an advice used to run on the half-initialized lazy aspect: PHP reported an uninitialized property at best, an advice reading no property ran without any error (#783). -* [Feature] **Weaving classes whose ancestors Composer can not locate** — the new `Features::PARTIAL_REFLECTION` flag reflects classes with the partial policy of goaop/parser-reflection 4.1/5.1 (`MissingAncestorPolicy::Partial`, applied by `AspectKernel::init()`): a parent class, interface or trait declared by code generated at runtime, by a `class_alias()` or in a file outside the Composer autoloader no longer fails the file (and `cache:warmup:aop`). The class is matched and woven with its own methods and properties and the ones of its available ancestors; members inherited from a missing ancestor are not intercepted. The proxy still declares the missing parent class and interfaces, which must be loaded by the time the class is. Without the flag such a class fails to weave, as before. +* [Feature] **Weaving classes whose ancestors Composer can not locate** — the new `Features::PARTIAL_REFLECTION` flag reflects classes with the partial policy of goaop/parser-reflection 4.2/5.2 (`MissingAncestorPolicy::Partial`, applied by `AspectKernel::init()`): a parent class, interface or trait declared by code generated at runtime, by a `class_alias()` or in a file outside the Composer autoloader no longer fails the file (and `cache:warmup:aop`). The class is matched and woven with its own methods and properties and the ones of its available ancestors; members inherited from a missing ancestor are not intercepted. The proxy still declares the missing parent class and interfaces, which must be loaded by the time the class is. Without the flag such a class fails to weave, as before. * [Feature] **Hint for classes Composer can not locate** — when weaving fails because goaop/parser-reflection can not find the source of a parent class, interface or trait (code generated at runtime, a `class_alias()`, a file outside the Composer autoloader), the `WeavingException` tells how to make the class loadable or to exclude the classes depending on it with `excludePaths` (#782). **Changed** diff --git a/composer.json b/composer.json index e60b9e0e..c35e122f 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,7 @@ "php": "^8.4.0", "ext-tokenizer": "*", "goaop/dissect": "^4.0", - "goaop/parser-reflection": "^4.1.0 || ^5.1.0", + "goaop/parser-reflection": "^4.2.0 || ^5.2.0", "psr/container": "^1.1 || ^2.0", "symfony/finder": "^7.4 || ^8.0" }, diff --git a/src/Instrument/AGENTS.md b/src/Instrument/AGENTS.md index 10c0bb0e..32d7c041 100644 --- a/src/Instrument/AGENTS.md +++ b/src/Instrument/AGENTS.md @@ -116,14 +116,16 @@ The check (`implementsInterface(Aspect::class)`) runs in WeavingTransformer::wea ## Partial reflection: ancestors that can't be located (Features::PARTIAL_REFLECTION) Opt-in. AspectKernel::init() → configureReflection() sets -`ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Partial)` (goaop/parser-reflection 4.1/5.1) when the +`ReflectionEngine::setMissingAncestorPolicy(MissingAncestorPolicy::Partial)` (goaop/parser-reflection 4.2/5.2) when the flag is on, and leaves the engine alone otherwise (strict: a missing ancestor fails the class, WeavingException hint #782). With the flag, a parent class, interface or trait whose source the locator can't find (generated at runtime, `class_alias()`, outside the Composer autoloader) is left out of the reflection instead of failing the class. Consequences: - Matching sees the class's own members and the ones of its available ancestors; members inherited from a missing ancestor are never matched, so never intercepted. -- The proxy must still declare the missing parent/interfaces: ClassProxyGenerator::getMissingDeclaredAncestors() adds the - direct ones (`isPartial()`/`getMissingClassNames()` ∩ names resolved from the class node) to `extends`/`implements`. - Ancestors missing further up come with the available ancestor. Missing traits need nothing: the `use` stays in the trait body. +- The proxy must still declare the missing parent/interfaces. ClassProxyGenerator takes the parent from + `getParentClassName()` of the parsed reflection (the name as written, located or not) and the interfaces from + `getInterfaceNames()`, which names the missing ones of a partial reflection; EnumProxyGenerator needs nothing more. + Never read the class node for this: names of ancestors are parser-reflection's job. Missing traits need nothing: the + `use` stays in the trait body. A matching failure on an aspect is swallowed (aspects used to be skipped before matching); on other classes it is rethrown. diff --git a/src/Proxy/ClassProxyGenerator.php b/src/Proxy/ClassProxyGenerator.php index 8410d892..8e78d6c7 100644 --- a/src/Proxy/ClassProxyGenerator.php +++ b/src/Proxy/ClassProxyGenerator.php @@ -28,7 +28,6 @@ use Go\Aop\StaticInitializationAware; use Go\Core\AspectContainer; use Go\ParserReflection\ReflectionClass as ParsedReflectionClass; -use Go\ParserReflection\ReflectionEnum as ParsedReflectionEnum; use Go\Proxy\Generator\AttributeGroupsGenerator; use Go\Proxy\Generator\ClassGenerator; use Go\Proxy\Generator\ClassModifier; @@ -53,12 +52,9 @@ use PhpParser\Node\Expr\StaticCall; use PhpParser\Node\Expr\Variable; use PhpParser\Node\Name; -use PhpParser\Node\Name\FullyQualified; use PhpParser\Node\Scalar\String_; use PhpParser\Node\Stmt; -use PhpParser\Node\Stmt\Class_; use PhpParser\Node\Stmt\ClassMethod; -use PhpParser\Node\Stmt\Enum_; use PhpParser\Node\Stmt\Expression; use PhpParser\Node\VariadicPlaceholder; use ReflectionClass; @@ -165,13 +161,9 @@ public function __construct( $generatedProperties[] = $interceptedProperty; } - // Proxy implements the same interfaces as the original class (no longer inherited), the ones a partial - // reflection leaves out included - [$missingParentName, $missingInterfaceNames] = self::getMissingDeclaredAncestors($originalClass); - $originalInterfaces = array_map( - self::rootClassName(...), - [...$originalClass->getInterfaceNames(), ...$missingInterfaceNames], - ); + // Proxy implements the same interfaces as the original class (no longer inherited); a partial reflection + // (Features::PARTIAL_REFLECTION) names the interfaces it can not locate too + $originalInterfaces = array_map(static fn(string $i) => '\\' . $i, $originalClass->getInterfaceNames()); $introducedInterfaces = array_merge($originalInterfaces, $introducedInterfaces); $introducedInterfaces[] = '\\' . Proxy::class; $introducedInterfaces = array_values(array_unique($introducedInterfaces)); @@ -193,13 +185,15 @@ public function __construct( } $introducedInterfaces = array_values(array_unique($introducedInterfaces)); - // Proxy parent = original class parent (not the trait — there is no inheritance layer) - $parentClass = $originalClass->getParentClass(); - $parentClassName = match (true) { - $parentClass !== false => '\\' . $parentClass->getName(), - $missingParentName !== null => self::rootClassName($missingParentName), - default => null, - }; + // Proxy parent = original class parent (not the trait — there is no inheritance layer). The parsed reflection + // names it as written in the source, also one it can not locate (Features::PARTIAL_REFLECTION) + if ($originalClass instanceof ParsedReflectionClass) { + $parentName = $originalClass->getParentClassName(); + } else { + $parentClass = $originalClass->getParentClass(); + $parentName = $parentClass !== false ? $parentClass->getName() : false; + } + $parentClassName = $parentName !== false ? self::rootClassName($parentName) : null; // Proxy modifiers: preserve final/abstract/readonly from original class. $modifiers = []; @@ -580,54 +574,6 @@ protected static function shortClassName(string $className): string return $lastSeparator === false ? $className : substr($className, $lastSeparator + 1); } - /** - * Parent class and interfaces declared by the original class whose source goaop/parser-reflection could not locate - * - * With Features::PARTIAL_REFLECTION the weaver reflects classes partially: a parent class or an interface declared - * in code generated at runtime, by a class_alias() or outside the Composer autoloader is left out of - * getParentClass() and getInterfaceNames(). The proxy still declares it under the name resolved from the source: - * the original class could not be loaded without it either. - * - * @param ReflectionClass $originalClass - * - * @return array{string|null, list} Name of the missing parent class (null if none), names of the - * missing interfaces - */ - protected static function getMissingDeclaredAncestors(ReflectionClass $originalClass): array - { - if (!$originalClass instanceof ParsedReflectionClass && !$originalClass instanceof ParsedReflectionEnum) { - return [null, []]; - } - $missingNames = $originalClass->getMissingClassNames(); - if ($missingNames === []) { - return [null, []]; - } - - $classNode = $originalClass->getNode(); - $parentName = $classNode instanceof Class_ && $classNode->extends !== null - ? self::resolvedName($classNode->extends) - : null; - $interfaceNames = $classNode instanceof Class_ || $classNode instanceof Enum_ - ? array_map(self::resolvedName(...), $classNode->implements) - : []; - - // Missing names include the ancestors missing for an available ancestor, which come with that one - return [ - in_array($parentName, $missingNames, true) ? $parentName : null, - array_values(array_intersect($interfaceNames, $missingNames)), - ]; - } - - /** - * Fully qualified name of a class referenced in the source - */ - private static function resolvedName(Name $name): string - { - $resolvedName = $name->getAttribute('resolvedName'); - - return $resolvedName instanceof FullyQualified ? $resolvedName->toString() : $name->toString(); - } - /** * Returns the class name rooted with a leading backslash, so that it is emitted fully qualified */ diff --git a/src/Proxy/EnumProxyGenerator.php b/src/Proxy/EnumProxyGenerator.php index acdd6f59..1fcb3c92 100644 --- a/src/Proxy/EnumProxyGenerator.php +++ b/src/Proxy/EnumProxyGenerator.php @@ -124,10 +124,8 @@ public function __construct( // Built-in PHP enum interfaces (UnitEnum, BackedEnum) are excluded: PHP applies them // automatically when the `enum` keyword is used, and listing them explicitly in a // namespaced file would resolve them as e.g. Ns\UnitEnum instead of the global \UnitEnum. - // Interfaces left out of a partial reflection are declared too, see getMissingDeclaredAncestors() - [, $missingInterfaceNames] = self::getMissingDeclaredAncestors($originalClass); $originalInterfaces = array_filter( - [...$originalClass->getInterfaceNames(), ...$missingInterfaceNames], + $originalClass->getInterfaceNames(), static fn(string $i) => !in_array($i, self::BUILTIN_ENUM_INTERFACES, true), ); $originalInterfaces = array_map(static fn(string $i) => '\\' . $i, $originalInterfaces);