diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a9d42b9..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.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.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,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] **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 b172e859..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.0.2 || ^5.0.2", + "goaop/parser-reflection": "^4.2.0 || ^5.2.0", "psr/container": "^1.1 || ^2.0", "symfony/finder": "^7.4 || ^8.0" }, @@ -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 866f4965..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; @@ -51,13 +52,17 @@ 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.', 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); @@ -196,8 +201,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. 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 { @@ -209,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 629b6b30..87b62e4d 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 + - 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/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 1baf5e44..32d7c041 100644 --- a/src/Instrument/AGENTS.md +++ b/src/Instrument/AGENTS.md @@ -112,5 +112,20 @@ 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 (Features::PARTIAL_REFLECTION) +Opt-in. AspectKernel::init() → configureReflection() sets +`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 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/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..8e78d6c7 100644 --- a/src/Proxy/ClassProxyGenerator.php +++ b/src/Proxy/ClassProxyGenerator.php @@ -27,6 +27,7 @@ use Go\Aop\Proxy; use Go\Aop\StaticInitializationAware; use Go\Core\AspectContainer; +use Go\ParserReflection\ReflectionClass as ParsedReflectionClass; use Go\Proxy\Generator\AttributeGroupsGenerator; use Go\Proxy\Generator\ClassGenerator; use Go\Proxy\Generator\ClassModifier; @@ -160,7 +161,8 @@ public function __construct( $generatedProperties[] = $interceptedProperty; } - // Proxy implements the same interfaces as the original class (no longer inherited) + // 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; @@ -183,9 +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 = $parentClass !== false ? '\\' . $parentClass->getName() : 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 = []; diff --git a/tests/Aop/Exception/ExceptionMessagesTest.php b/tests/Aop/Exception/ExceptionMessagesTest.php index 22cd314c..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; @@ -331,12 +332,27 @@ 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.', ], + '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', @@ -346,8 +362,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..77d6fb11 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,35 @@ private function getInheritanceAdvices( return new AdviceMatcher($isWovenFile)->getAdvicesForClass(new ReflectionClass($className), ['advisor' => $advisor]); } + /** + * 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::Partial); + try { + $class = new ReflectionFile(dirname(__DIR__) . '/Instrument/Transformer/_files/class-unknown-parent.php') + ->getFileNamespace('Test\ns1') + ->getClass('Test\ns1\RuleWithMissingParent'); + + $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->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/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/partial/Issue251ReportController.php b/tests/Fixtures/project/partial/Issue251ReportController.php new file mode 100644 index 00000000..c2139272 --- /dev/null +++ b/tests/Fixtures/project/partial/Issue251ReportController.php @@ -0,0 +1,28 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +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. 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 +{ + 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..f57fd742 --- /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\Partial\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/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/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..be926280 --- /dev/null +++ b/tests/Functional/PartialReflectionWeavingTest.php @@ -0,0 +1,75 @@ + + * + * 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\Partial\Issue251ReportController; + +/** + * 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 +{ + 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; + + 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 + */ + 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..9839dab8 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 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 + { + $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. */