Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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**
Expand Down
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 24 additions & 3 deletions src/Aop/Exception/WeavingException.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

namespace Go\Aop\Exception;

use Go\ParserReflection\ClassNotFoundException;
use RuntimeException;
use Throwable;

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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
{
Expand All @@ -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;
}
}
14 changes: 13 additions & 1 deletion src/Aop/Features.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions src/Core/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions src/Core/AspectKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -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']);
}
Expand Down Expand Up @@ -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
*
Expand Down
17 changes: 16 additions & 1 deletion src/Instrument/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
4 changes: 2 additions & 2 deletions src/Instrument/Transformer/WeavingTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}

Expand Down
16 changes: 12 additions & 4 deletions src/Proxy/ClassProxyGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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 = [];
Expand Down
Loading
Loading