From 70d91acee190a2b06a051974b2146805125d5121 Mon Sep 17 00:00:00 2001 From: WalterWoshid Date: Fri, 13 Nov 2026 22:22:42 +0100 Subject: [PATCH] feat(advice): add filtered AfterThrowing advice Add exception filtering and getThrowable(), preserving the original throwable after advice execution. Preserve repeated declarations, method filters, and execution order through weaving and cache restoration. Invalidate legacy caches. Add documentation and regression tests. --- README.md | 49 ++- docs/architecture.md | 20 +- src/Advice/AdviceType.php | 1 - src/Attributes/AfterThrowing.php | 44 +++ .../Attributes/AdviceType/MethodAdvice.php | 2 + src/Core/Cache/CacheStateManager.php | 5 +- src/Core/Container/AdviceContainerFactory.php | 3 + .../AdviceType/MethodAdviceContainer.php | 6 +- src/Core/Container/AspectManager.php | 3 +- src/Core/Factory/InvocationFactory.php | 22 +- src/Core/Intercept/Interceptor.php | 45 ++- src/Core/JoinPoint/JoinPointHandler.php | 20 +- src/Core/Transform/WovenClassBuilder.php | 5 +- .../AfterThrowingMethodInvocation.php | 32 ++ src/Invocation/MethodInvocation.php | 6 +- .../AfterThrowing/AfterThrowingTest.php | 322 ++++++++++++++++++ .../AfterThrowing/ClassTarget.php | 14 + .../AfterThrowing/ExplicitAspect.php | 20 ++ .../AfterThrowing/ExplicitKernel.php | 9 + .../AfterThrowing/FailureAspect.php | 81 +++++ .../AfterThrowing/FilteredAspect.php | 47 +++ .../AfterThrowing/FilteredTarget.php | 18 + .../AdviceBehavior/AfterThrowing/Kernel.php | 14 + .../AfterThrowing/MethodTarget.php | 14 + .../AfterThrowing/RepeatedAspect.php | 32 ++ .../AfterThrowing/RepeatedTarget.php | 23 ++ .../AdviceBehavior/AfterThrowing/State.php | 17 + .../AdviceBehavior/AfterThrowing/Target.php | 32 ++ .../AfterThrowing/AfterThrowingFilterTest.php | 52 +++ 29 files changed, 930 insertions(+), 28 deletions(-) create mode 100644 src/Attributes/AfterThrowing.php create mode 100644 src/Invocation/AfterThrowingMethodInvocation.php create mode 100644 tests/Functional/AdviceBehavior/AfterThrowing/AfterThrowingTest.php create mode 100644 tests/Functional/AdviceBehavior/AfterThrowing/ClassTarget.php create mode 100644 tests/Functional/AdviceBehavior/AfterThrowing/ExplicitAspect.php create mode 100644 tests/Functional/AdviceBehavior/AfterThrowing/ExplicitKernel.php create mode 100644 tests/Functional/AdviceBehavior/AfterThrowing/FailureAspect.php create mode 100644 tests/Functional/AdviceBehavior/AfterThrowing/FilteredAspect.php create mode 100644 tests/Functional/AdviceBehavior/AfterThrowing/FilteredTarget.php create mode 100644 tests/Functional/AdviceBehavior/AfterThrowing/Kernel.php create mode 100644 tests/Functional/AdviceBehavior/AfterThrowing/MethodTarget.php create mode 100644 tests/Functional/AdviceBehavior/AfterThrowing/RepeatedAspect.php create mode 100644 tests/Functional/AdviceBehavior/AfterThrowing/RepeatedTarget.php create mode 100644 tests/Functional/AdviceBehavior/AfterThrowing/State.php create mode 100644 tests/Functional/AdviceBehavior/AfterThrowing/Target.php create mode 100644 tests/Integration/AfterThrowing/AfterThrowingFilterTest.php diff --git a/README.md b/README.md index dea8fed..8e22236 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,7 @@ composer require okapi/aop target classes. Aspects must be annotated with the `#[Aspect]` attribute. - **Advice**: The logic that you want to apply to your target classes. Advice - methods must be annotated with the `#[Before]`, `#[Around]` or `#[After]` + methods must be annotated with `#[Before]`, `#[Around]`, `#[After]`, or `#[AfterThrowing]` attributes. - **Join Point**: A point in the execution of your target classes where you can @@ -182,7 +182,7 @@ use Okapi\Aop\Invocation\AfterMethodInvocation; class DiscountAspect { // Annotate the methods that you want to intercept with - // "Before", "Around" or "After" attributes + // "Before", "Around", "After", or "AfterThrowing" attributes #[After( // Use named arguments // You can also use Wildcards (see Okapi/Wildcards package) @@ -307,6 +307,47 @@ class PaymentProcessorAspect ``` +### AfterThrowing advice + +`#[AfterThrowing]` runs when the intercepted target method throws an exception or +PHP error (`Throwable`). It receives the original throwable and the invocation +context: + +```php +use Okapi\Aop\Attributes\AfterThrowing; +use Okapi\Aop\Invocation\AfterThrowingMethodInvocation; + +// Inside an aspect: +#[AfterThrowing( + class: PaymentProcessor::class, + method: 'processPayment', + exception: \DomainException::class, +)] +public function logFailure(AfterThrowingMethodInvocation $invocation): void +{ + error_log($invocation->getThrowable()->getMessage()); +} +``` + +It supports the same class/method patterns, `order`, `interceptTraitMethods`, and +`onlyPublicMethods` options as the other method advice types, including explicit +class-level and method-level aspects. Advice runs in ascending `order`. + +The optional `exception` filter matches the given type and its subclasses. It +defaults to `Throwable::class`, which includes exceptions and PHP errors. Use +`Exception::class` to exclude errors, or `Error::class` to handle only errors. +An unknown type or a type that does not implement `Throwable` is rejected when the +advice attribute is instantiated. + +- Successful calls and exceptions caught inside the target do not trigger it. +- The original throwable is rethrown after the advice completes. Return values are + ignored; the invocation has no `proceed()` or `setResult()` method. +- It runs before an outer `Around` advice catches a target failure. Repeated target + calls through `proceed(true)` trigger it for each failure. +- Exceptions originating in `Before`, `Around`, or `After` advice do not trigger it. +- If an `AfterThrowing` advice throws, that new throwable propagates and remaining + `AfterThrowing` advice is skipped. + ### Regular-expression patterns `class` and `method` accept either wildcard strings or explicit @@ -324,7 +365,7 @@ use Okapi\Wildcards\Regex; This matches controller methods whose names start with a letter, excluding constructors and other magic methods. Regex objects can also be used for `class`. -The same arguments are supported by `Before`, `Around`, and `After`. +The same arguments are supported by `Before`, `Around`, `After`, and `AfterThrowing`. Pass a complete PHP regular expression, including delimiters and any modifiers. Regex patterns are used as written: add `^` and `$` when you want to match the @@ -709,7 +750,7 @@ $firstLog = $logs[0]; # Features -- **Advice types:** "Before", "Around" and "After" +- **Advice types:** "Before", "Around", "After", and "AfterThrowing" - Intercept "private" and "protected" methods (Will show errors in IDEs) diff --git a/docs/architecture.md b/docs/architecture.md index 2de4cd7..3fd787e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -125,7 +125,25 @@ flowchart TD This is the normal successful path. An exception interrupts it; `After` is not a `finally` handler. Missing advice groups are skipped. The configured advice order -is applied within the Before, Around, and After groups. +is applied within the Before, Around, After, and AfterThrowing groups. + +If an original target call throws a `Throwable`, the interceptor runs the matching +`AfterThrowing` advice in order and rethrows the same object. This happens inside +the original-method callback, before control returns to any surrounding Around +advice. Successful calls and failures originating in other advice skip this group. +AfterThrowing invocations expose `getThrowable()` and invocation context, without +`proceed()` or result replacement. If this advice itself throws, its throwable +propagates immediately and the remaining failure advice does not run. + +Each AfterThrowing attribute can restrict execution with an `exception` type +filter. Matching includes subclasses; the default `Throwable` +filter accepts both exceptions and errors. The filter is validated when the advice +attribute is instantiated, and is applied again on each failing target call. + +Join points and cached metadata identify each advice declaration by its aspect, +method, and attribute index. Repeated attributes retain their own method filters +and execution order. The cache hash includes the declaration format version so +older method-name-only caches are rebuilt, including caches of explicit aspects. An Around invocation's `proceed()` advances the chain. The original method can run inside that call; the Around advice then resumes and can modify the result. The diff --git a/src/Advice/AdviceType.php b/src/Advice/AdviceType.php index e41aa5b..41b0d24 100644 --- a/src/Advice/AdviceType.php +++ b/src/Advice/AdviceType.php @@ -14,6 +14,5 @@ enum AdviceType case After; // Reserved for future after-returning advice support. case AfterReturning; - // Reserved for future after-throwing advice support. case AfterThrowing; } diff --git a/src/Attributes/AfterThrowing.php b/src/Attributes/AfterThrowing.php new file mode 100644 index 0000000..8f10a88 --- /dev/null +++ b/src/Attributes/AfterThrowing.php @@ -0,0 +1,44 @@ + + */ + public readonly string $exception; + + /** + * @param string $exception The Throwable class or interface to match, + * including subclasses. + */ + public function __construct( + string|Regex|null $class = null, + string|Regex|null $method = null, + int $order = 0, + bool $interceptTraitMethods = true, + bool $onlyPublicMethods = false, + string $exception = Throwable::class, + ) { + parent::__construct($class, $method, $order, $interceptTraitMethods, $onlyPublicMethods); + + if (!is_a($exception, Throwable::class, true)) { + throw new InvalidArgumentException( + 'Invalid exception filter "' . $exception . '": expected a Throwable class or interface.', + ); + } + + $this->exception = $exception; + } +} diff --git a/src/Core/Attributes/AdviceType/MethodAdvice.php b/src/Core/Attributes/AdviceType/MethodAdvice.php index 40ed998..297d26a 100644 --- a/src/Core/Attributes/AdviceType/MethodAdvice.php +++ b/src/Core/Attributes/AdviceType/MethodAdvice.php @@ -3,6 +3,7 @@ namespace Okapi\Aop\Core\Attributes\AdviceType; use Okapi\Aop\Attributes\After; +use Okapi\Aop\Attributes\AfterThrowing; use Okapi\Aop\Attributes\Around; use Okapi\Aop\Attributes\Before; use Okapi\Aop\Core\Attributes\Base\BaseAdvice; @@ -17,6 +18,7 @@ * @see Before * @see Around * @see After + * @see AfterThrowing */ abstract class MethodAdvice extends BaseAdvice { diff --git a/src/Core/Cache/CacheStateManager.php b/src/Core/Cache/CacheStateManager.php index ab434f6..e8b11dd 100644 --- a/src/Core/Cache/CacheStateManager.php +++ b/src/Core/Cache/CacheStateManager.php @@ -12,6 +12,9 @@ */ class CacheStateManager extends CodeTransformerCacheStateManager { + // Invalidate method-name-only join points, including caches of explicit aspects. + private const ADVICE_DECLARATION_VERSION = 1; + // region DI #[Inject] @@ -29,7 +32,7 @@ protected function getHash(): string $transformerHash = parent::getHash(); $aspectAdviceNames = $this->aspectManager->getAspectAdviceNames(); - $aspectHash = md5(serialize($aspectAdviceNames)); + $aspectHash = md5(serialize([self::ADVICE_DECLARATION_VERSION, $aspectAdviceNames])); return $transformerHash . $aspectHash; } diff --git a/src/Core/Container/AdviceContainerFactory.php b/src/Core/Container/AdviceContainerFactory.php index 00e3830..c6b3aef 100644 --- a/src/Core/Container/AdviceContainerFactory.php +++ b/src/Core/Container/AdviceContainerFactory.php @@ -27,6 +27,7 @@ class AdviceContainerFactory * @param BaseReflectionClass $aspectRefClass * @param BaseReflectionAttribute $adviceAttribute * @param BaseReflectionMethod $adviceRefMethod + * @param int $declarationIndex * * @return AdviceContainer * @@ -38,6 +39,7 @@ public function createAdviceContainer( BaseReflectionClass $aspectRefClass, BaseReflectionAttribute $adviceAttribute, BaseReflectionMethod $adviceRefMethod, + int $declarationIndex = 0, ): AdviceContainer { // Instantiate the advice attribute $adviceAttributeInstance = $adviceAttribute->newInstance(); @@ -54,6 +56,7 @@ public function createAdviceContainer( 'adviceAttributeInstance' => $adviceAttributeInstance, 'adviceRefMethod' => $adviceRefMethod, 'isExplicit' => $isExplicit, + 'declarationIndex' => $declarationIndex, ]); // If the aspect is implicit, diff --git a/src/Core/Container/AdviceType/MethodAdviceContainer.php b/src/Core/Container/AdviceType/MethodAdviceContainer.php index 49359d5..f5aaa37 100644 --- a/src/Core/Container/AdviceType/MethodAdviceContainer.php +++ b/src/Core/Container/AdviceType/MethodAdviceContainer.php @@ -37,6 +37,7 @@ class MethodAdviceContainer extends AdviceContainer * @param MethodAdvice $adviceAttributeInstance * @param BaseReflectionMethod $adviceRefMethod * @param bool $isExplicit + * @param int $declarationIndex Position among the advice attributes on the method. */ public function __construct( string $aspectClassName, @@ -46,6 +47,7 @@ public function __construct( MethodAdvice $adviceAttributeInstance, public readonly BaseReflectionMethod $adviceRefMethod, private readonly bool $isExplicit, + private readonly int $declarationIndex = 0, ) { parent::__construct( $aspectClassName, @@ -81,13 +83,13 @@ public function getMatchedMethods(): array } /** - * Get advice name. + * Get the identity of this advice declaration. * * @return string */ public function getName(): string { - return $this->aspectClassName . '::' . $this->adviceRefMethod->getName(); + return $this->aspectClassName . '::' . $this->adviceRefMethod->getName() . '#' . $this->declarationIndex; } /** diff --git a/src/Core/Container/AspectManager.php b/src/Core/Container/AspectManager.php index c7d7137..58b74ca 100644 --- a/src/Core/Container/AspectManager.php +++ b/src/Core/Container/AspectManager.php @@ -161,13 +161,14 @@ public function loadAspect(mixed $aspectClassName): void ); // Create advice containers and store them - foreach ($adviceAttributes as $adviceAttribute) { + foreach ($adviceAttributes as $declarationIndex => $adviceAttribute) { $adviceContainer = $this->adviceContainerFactory->createAdviceContainer( $aspectClassName, $aspectInstance, $aspectRefClass, $adviceAttribute, $adviceRefMember, + $declarationIndex, ); $this->aspectAdviceContainers[$aspectClassName][] = $adviceContainer; diff --git a/src/Core/Factory/InvocationFactory.php b/src/Core/Factory/InvocationFactory.php index 55f1b28..5dabf22 100644 --- a/src/Core/Factory/InvocationFactory.php +++ b/src/Core/Factory/InvocationFactory.php @@ -2,15 +2,19 @@ namespace Okapi\Aop\Core\Factory; +use LogicException; use Okapi\Aop\Attributes\After; +use Okapi\Aop\Attributes\AfterThrowing; use Okapi\Aop\Attributes\Around; use Okapi\Aop\Attributes\Before; use Okapi\Aop\Core\Container\AdviceType\MethodAdviceContainer; use Okapi\Aop\Invocation\AfterMethodInvocation; +use Okapi\Aop\Invocation\AfterThrowingMethodInvocation; use Okapi\Aop\Invocation\AroundMethodInvocation; use Okapi\Aop\Invocation\BeforeMethodInvocation; use Okapi\Aop\Invocation\MethodInvocation; use Okapi\CodeTransformer\Core\DI; +use Throwable; /** * # Invocation Factory @@ -28,10 +32,9 @@ class InvocationFactory * @param string $methodName * @param mixed $result * @param array $arguments + * @param Throwable|null $throwable The target failure for AfterThrowing advice. * * @return MethodInvocation - * - * @noinspection PhpInconsistentReturnPointsInspection */ public function getInvocation( MethodAdviceContainer $adviceContainer, @@ -40,8 +43,21 @@ public function getInvocation( string $methodName, mixed $result, array &$arguments, + ?Throwable $throwable = null, ): MethodInvocation { switch (true) { + case $adviceContainer->adviceAttributeInstance instanceof AfterThrowing: + if ($throwable === null) { + throw new LogicException('AfterThrowing advice requires a target throwable.'); + } + return DI::make(AfterThrowingMethodInvocation::class, [ + 'subject' => $subject, + 'className' => $className, + 'methodName' => $methodName, + 'arguments' => &$arguments, + 'throwable' => $throwable, + ]); + // Before case $adviceContainer->adviceAttributeInstance instanceof Before: return DI::make(BeforeMethodInvocation::class, [ @@ -72,6 +88,6 @@ public function getInvocation( 'arguments' => &$arguments, ]); } - throw new \LogicException('Unsupported advice type.'); + throw new LogicException('Unsupported advice type.'); } } diff --git a/src/Core/Intercept/Interceptor.php b/src/Core/Intercept/Interceptor.php index 9512c55..241a3d9 100644 --- a/src/Core/Intercept/Interceptor.php +++ b/src/Core/Intercept/Interceptor.php @@ -4,6 +4,8 @@ namespace Okapi\Aop\Core\Intercept; use DI\Attribute\Inject; +use LogicException; +use Okapi\Aop\Attributes\AfterThrowing; use Okapi\Aop\Core\Container\AdviceType\MethodAdviceContainer; use Okapi\Aop\Core\Factory\InvocationFactory; use Okapi\Aop\Core\Invocation\AdviceChain; @@ -11,6 +13,7 @@ use Okapi\CodeTransformer\Core\DI; use ReflectionClass as BaseReflectionClass; use ReflectionMethod; +use Throwable; /** * # Interceptor @@ -37,6 +40,11 @@ class Interceptor /** @var MethodAdviceContainer[] */ private array $afterInterceptors = []; + /** + * @var MethodAdviceContainer[] + */ + private array $afterThrowingInterceptors = []; + /** * The target class reflection. * @@ -64,7 +72,12 @@ public function __construct( 'joinPoints' => $joinPoints, ]); - $joinPointHandler->handle($this->beforeInterceptors, $this->aroundInterceptors, $this->afterInterceptors); + $joinPointHandler->handle( + $this->beforeInterceptors, + $this->aroundInterceptors, + $this->afterInterceptors, + $this->afterThrowingInterceptors, + ); $this->targetRefClass = new BaseReflectionClass($className); } @@ -158,13 +171,36 @@ private function callParentMethod(?object $subject, array $args): mixed $parentClass = $this->targetRefClass->getParentClass(); if ($parentClass === false) { - throw new \LogicException('An intercepted class must have a woven parent.'); + throw new LogicException('An intercepted class must have a woven parent.'); } $parentMethod = $parentClass->getMethod($this->methodName); + $invocationArguments = $args; $this->unwrapVariadicParameters($parentMethod, $args); - return $parentMethod->invokeArgs($subject, array_values($args)); + try { + return $parentMethod->invokeArgs($subject, array_values($args)); + } catch (Throwable $throwable) { + foreach ($this->afterThrowingInterceptors as $interceptor) { + $advice = $interceptor->adviceAttributeInstance; + if (!$advice instanceof AfterThrowing || !is_a($throwable::class, $advice->exception, true)) { + continue; + } + + $invocation = $this->invocationFactory->getInvocation( + adviceContainer: $interceptor, + subject: $subject, + className: $this->className, + methodName: $this->methodName, + result: null, + arguments: $invocationArguments, + throwable: $throwable, + ); + + $interceptor->adviceRefMethod->invoke($interceptor->aspectInstance, $invocation); + } + throw $throwable; + } } /** @@ -187,8 +223,9 @@ private function unwrapVariadicParameters(ReflectionMethod $method, array &$args /** @var mixed $variadicArguments */ $variadicArguments = $args[$lastParameterName]; if (!is_array($variadicArguments)) { - throw new \LogicException('Variadic arguments must be an array.'); + throw new LogicException('Variadic arguments must be an array.'); } + $variadicParameterValues = array_values($variadicArguments); unset($args[$lastParameterName]); diff --git a/src/Core/JoinPoint/JoinPointHandler.php b/src/Core/JoinPoint/JoinPointHandler.php index 5c25fd2..0128548 100644 --- a/src/Core/JoinPoint/JoinPointHandler.php +++ b/src/Core/JoinPoint/JoinPointHandler.php @@ -5,8 +5,10 @@ use DI\Attribute\Inject; use Okapi\Aop\Attributes\After; +use Okapi\Aop\Attributes\AfterThrowing; use Okapi\Aop\Attributes\Around; use Okapi\Aop\Attributes\Before; +use Okapi\Aop\Core\Container\AdviceType\MethodAdviceContainer; use Okapi\Aop\Core\Matcher\AspectMatcher; /** @@ -37,14 +39,19 @@ public function __construct( /** * Add the matched advices to the given interceptor arrays. * - * @param \Okapi\Aop\Core\Container\AdviceType\MethodAdviceContainer[] $beforeInterceptors - * @param \Okapi\Aop\Core\Container\AdviceType\MethodAdviceContainer[] $aroundInterceptors - * @param \Okapi\Aop\Core\Container\AdviceType\MethodAdviceContainer[] $afterInterceptors + * @param MethodAdviceContainer[] $beforeInterceptors + * @param MethodAdviceContainer[] $aroundInterceptors + * @param MethodAdviceContainer[] $afterInterceptors + * @param MethodAdviceContainer[] $afterThrowingInterceptors * * @return void */ - public function handle(array &$beforeInterceptors, array &$aroundInterceptors, array &$afterInterceptors): void - { + public function handle( + array &$beforeInterceptors, + array &$aroundInterceptors, + array &$afterInterceptors, + array &$afterThrowingInterceptors = [], + ): void { foreach ($this->joinPoints as $joinPoint) { $adviceContainers = $this->aspectMatcher->getMatchedAdviceContainersByJoinPoint( $this->className, @@ -54,6 +61,9 @@ public function handle(array &$beforeInterceptors, array &$aroundInterceptors, a foreach ($adviceContainers as $adviceContainer) { $adviceAttributeInstance = $adviceContainer->adviceAttributeInstance; switch (true) { + case $adviceAttributeInstance instanceof AfterThrowing: + $afterThrowingInterceptors[] = $adviceContainer; + break; case $adviceAttributeInstance instanceof Before: $beforeInterceptors[] = $adviceContainer; break; diff --git a/src/Core/Transform/WovenClassBuilder.php b/src/Core/Transform/WovenClassBuilder.php index 0d81971..41f4599 100644 --- a/src/Core/Transform/WovenClassBuilder.php +++ b/src/Core/Transform/WovenClassBuilder.php @@ -224,7 +224,6 @@ private function buildMethods(): array private function buildMethod(BetterReflectionMethod $refMethod): Method { $refMethod = new ReflectionMethod($refMethod); - /** @noinspection PhpUnhandledExceptionInspection */ $method = (new Factory())->fromMethodReflection($refMethod); $methodName = $refMethod->getName(); @@ -247,8 +246,8 @@ private function buildMethod(BetterReflectionMethod $refMethod): Method } $method->setParameters(array_values($parameters)); - // Add "return" if the method has a return type - $return = (string) $method->getReturnType() !== 'void' ? 'return ' : ''; + // Void and never methods cannot contain a return value. + $return = in_array((string) $method->getReturnType(), ['void', 'never'], true) ? '' : 'return '; // Add parameters as an array with the parameter name as key $parametersArray = $this->getParametersArray($refMethod); diff --git a/src/Invocation/AfterThrowingMethodInvocation.php b/src/Invocation/AfterThrowingMethodInvocation.php new file mode 100644 index 0000000..f3f8fed --- /dev/null +++ b/src/Invocation/AfterThrowingMethodInvocation.php @@ -0,0 +1,32 @@ + $arguments + */ + public function __construct( + ?object $subject, + string $className, + string $methodName, + array &$arguments, + private readonly Throwable $throwable, + ) { + parent::__construct( + subject: $subject, + className: $className, + methodName: $methodName, + result: null, + arguments: $arguments, + ); + } + + public function getThrowable(): Throwable + { + return $this->throwable; + } +} diff --git a/src/Invocation/MethodInvocation.php b/src/Invocation/MethodInvocation.php index 64bdb38..75910c1 100644 --- a/src/Invocation/MethodInvocation.php +++ b/src/Invocation/MethodInvocation.php @@ -3,6 +3,7 @@ namespace Okapi\Aop\Invocation; use Okapi\Aop\Advice\AdviceType; +use UnhandledMatchError; /** * # Method invocation @@ -86,8 +87,6 @@ public function setArguments(array $arguments): void * Get the advice type of the invocation. * * @return AdviceType - * - * @noinspection PhpUndefinedClassInspection */ public function getAdviceType(): AdviceType { @@ -95,7 +94,8 @@ public function getAdviceType(): AdviceType $this instanceof AroundMethodInvocation => AdviceType::Around, $this instanceof BeforeMethodInvocation => AdviceType::Before, $this instanceof AfterMethodInvocation => AdviceType::After, - default => throw new \UnhandledMatchError('Unsupported advice invocation type.'), + $this instanceof AfterThrowingMethodInvocation => AdviceType::AfterThrowing, + default => throw new UnhandledMatchError('Unsupported advice invocation type.'), }; } diff --git a/tests/Functional/AdviceBehavior/AfterThrowing/AfterThrowingTest.php b/tests/Functional/AdviceBehavior/AfterThrowing/AfterThrowingTest.php new file mode 100644 index 0000000..e78d528 --- /dev/null +++ b/tests/Functional/AdviceBehavior/AfterThrowing/AfterThrowingTest.php @@ -0,0 +1,322 @@ +initialize(); + static::assertSame('updated3', (new Target())->run('success', null, 'original', 1, 2)); + static::assertSame([], State::$invocations); + static::assertSame(['target', 'after'], State::$events); + } + + public function testExceptionIdentityOrderAndInvocationContext(): void + { + $this->initialize(); + $this->assertWillBeWoven(Target::class); + $target = new Target(); + $exception = new RuntimeException('target failure'); + $this->assertThrownSame($exception, static fn() => $target->run('fail', $exception, 'original', 1, 2)); + static::assertSame(['target', 'early', 'late'], State::$events); + static::assertCount(2, State::$invocations); + foreach (State::$invocations as $invocation) { + static::assertSame($exception, $invocation->getThrowable()); + static::assertSame($target, $invocation->getSubject()); + static::assertSame(Target::class, $invocation->getClassName()); + static::assertSame('run', $invocation->getMethodName()); + static::assertSame('updated', $invocation->getArgument('label')); + static::assertSame([1, 2], $invocation->getArgument('values')); + static::assertSame(AdviceType::AfterThrowing, $invocation->getAdviceType()); + static::assertFalse(method_exists($invocation, 'proceed')); + static::assertFalse(method_exists($invocation, 'setResult')); + } + } + + public function testErrorsAlsoTriggerAdvice(): void + { + $this->initialize(); + $error = new Error('target error'); + $this->assertThrownSame($error, static fn() => (new Target())->run('fail', $error)); + static::assertSame($error, State::$invocations[0]->getThrowable()); + static::assertSame(['target', 'early', 'late'], State::$events); + } + + public function testStaticMethod(): void + { + $this->initialize(); + $exception = new RuntimeException('static failure'); + $this->assertThrownSame($exception, static fn() => Target::failStatic($exception)); + static::assertSame(['early', 'late'], State::$events); + static::assertNull(State::$invocations[0]->getSubject()); + static::assertSame('failStatic', State::$invocations[0]->getMethodName()); + } + + public function testNeverMethod(): void + { + $this->initialize(); + $exception = new RuntimeException('never failure'); + $this->assertThrownSame($exception, static fn() => (new Target())->failNever($exception)); + static::assertSame(['early', 'late'], State::$events); + } + + public function testUnmatchedMethodDoesNotTriggerAdvice(): void + { + $this->initialize(); + $exception = new RuntimeException('unmatched'); + $this->assertThrownSame($exception, static fn() => (new Target())->unmatched($exception)); + static::assertSame([], State::$invocations); + } + + public function testAroundCanRecoverAfterAfterThrowingRuns(): void + { + $this->initialize(); + static::assertSame('recovered', (new Target())->run('recover', new RuntimeException('target'))); + static::assertSame(['target', 'early', 'late', 'caught', 'after'], State::$events); + } + + public function testAroundShortCircuitDoesNotTriggerAdvice(): void + { + $this->initialize(); + static::assertSame('short', (new Target())->run('short', new RuntimeException('unused'))); + static::assertSame(['after'], State::$events); + static::assertSame([], State::$invocations); + } + + public function testRepeatedTargetCallsNotifyForEachFailure(): void + { + $this->initialize(); + $exception = new RuntimeException('target'); + $this->assertThrownSame($exception, static fn() => (new Target())->run('retry', $exception)); + static::assertSame(['target', 'early', 'late', 'caught', 'target', 'early', 'late'], State::$events); + } + + public function testOtherAdviceFailuresDoNotTriggerAfterThrowing(): void + { + $this->initialize(); + foreach (['before', 'around', 'after'] as $mode) { + try { + (new Target())->run($mode); + static::fail('Expected advice failure.'); + } catch (RuntimeException $exception) { + static::assertSame($mode, $exception->getMessage()); + } + } + static::assertSame([], State::$invocations); + } + + public function testAfterThrowingFailurePropagatesWithoutRecursion(): void + { + $this->initialize(); + $replacement = new RuntimeException('observer'); + State::$observerFailure = $replacement; + $this->assertThrownSame($replacement, static fn() => (new Target())->run( + 'fail', + new RuntimeException('target'), + )); + static::assertSame(['target', 'early'], State::$events); + } + + public function testExplicitClassAndMethodAspects(): void + { + $this->initialize(); + $exception = new RuntimeException('explicit'); + $classTarget = new ClassTarget(); + $methodTarget = new MethodTarget(); + $this->assertThrownSame($exception, static fn() => $classTarget->fail($exception)); + $this->assertThrownSame($exception, static fn() => $methodTarget->fail($exception)); + static::assertCount(2, State::$invocations); + static::assertSame($classTarget, State::$invocations[0]->getSubject()); + static::assertSame($methodTarget, State::$invocations[1]->getSubject()); + $error = new Error('not an exception'); + $this->assertThrownSame($error, static fn() => $classTarget->fail($error)); + $this->assertThrownSame($error, static fn() => $methodTarget->fail($error)); + static::assertCount(2, State::$invocations); + } + + /** @return array, list}> */ + public static function filteredFailures(): array + { + return [ + 'exact exception' => [RuntimeException::class, ['runtime', 'exception', 'throwable']], + 'exception subclass' => [UnexpectedValueException::class, ['runtime', 'exception', 'throwable']], + 'unrelated exception' => [LogicException::class, ['exception', 'throwable']], + 'exact error' => [Error::class, ['error', 'throwable']], + 'error subclass' => [TypeError::class, ['error', 'throwable']], + ]; + } + + /** + * @param class-string $type + * @param list $events + */ + #[DataProvider('filteredFailures')] + public function testFiltersIncludeSubclassesAndPreserveOrder(string $type, array $events): void + { + $this->initialize(); + $throwable = match ($type) { + RuntimeException::class => new RuntimeException(), + UnexpectedValueException::class => new UnexpectedValueException(), + LogicException::class => new LogicException(), + Error::class => new Error(), + TypeError::class => new TypeError(), + default => throw new LogicException('Unknown throwable fixture.'), + }; + $this->assertThrownSame($throwable, static fn() => (new FilteredTarget())->fail($throwable)); + static::assertSame($events, State::$events); + foreach (State::$invocations as $invocation) { + static::assertSame($throwable, $invocation->getThrowable()); + } + } + + public function testUnmatchedExceptionFilterStillRethrowsOriginal(): void + { + $this->initialize(); + $throwable = new LogicException('unmatched filter'); + $this->assertThrownSame($throwable, static fn() => (new FilteredTarget())->runtimeOnly($throwable)); + static::assertSame([], State::$events); + } + + public function testCachedTargetRetainsAfterThrowingAdvice(): void + { + Util::clearCache(); + $this->warmCache(Kernel::class, [Target::class, FilteredTarget::class, RepeatedTarget::class]); + Kernel::init(); + $this->assertAspectLoadedFromCache(Target::class); + $this->assertAspectLoadedFromCache(FilteredTarget::class); + $this->assertAspectLoadedFromCache(RepeatedTarget::class); + $exception = new RuntimeException('cached'); + $this->assertThrownSame($exception, static fn() => (new Target())->run('fail', $exception)); + static::assertSame(['target', 'early', 'late'], State::$events); + $error = new TypeError('cached error'); + $this->assertThrownSame($error, static fn() => (new FilteredTarget())->fail($error)); + static::assertSame(['target', 'early', 'late', 'error', 'throwable'], State::$events); + $this->assertRepeatedDeclarations(); + } + + public function testCachedExplicitAspectsRetainFiltering(): void + { + Util::clearCache(); + $this->warmCache(ExplicitKernel::class, [ClassTarget::class, MethodTarget::class]); + ExplicitKernel::init(); + $this->assertAspectLoadedFromCache(ClassTarget::class); + $this->assertAspectLoadedFromCache(MethodTarget::class); + $exception = new RuntimeException('cached explicit'); + $error = new Error('not an exception'); + $this->assertThrownSame($exception, static fn() => (new ClassTarget())->fail($exception)); + $this->assertThrownSame($exception, static fn() => (new MethodTarget())->fail($exception)); + $this->assertThrownSame($error, static fn() => (new ClassTarget())->fail($error)); + $this->assertThrownSame($error, static fn() => (new MethodTarget())->fail($error)); + static::assertCount(2, State::$invocations); + } + + public function testLegacyExplicitCacheIsRebuilt(): void + { + Util::clearCache(); + $this->warmCache(ExplicitKernel::class, [ClassTarget::class]); + /** @var mixed $cache */ + $cache = require Util::CACHE_STATES_FILE; + static::assertIsArray($cache); + /** @var mixed $hash */ + $hash = $cache[CacheStateManager::HASH] ?? null; + static::assertIsString($hash); + // Old caches hash only registered advice names; explicit-only kernels have none. + $cache[CacheStateManager::HASH] = substr($hash, 0, 32) . md5(serialize([])); + $contents = str_replace('::observe#0', '::observe', 'assertWillBeWoven(ClassTarget::class); + $exception = new RuntimeException('rebuilt'); + $this->assertThrownSame($exception, static fn() => (new ClassTarget())->fail($exception)); + static::assertCount(1, State::$invocations); + } + + /** + * @param class-string $kernel + * @param list $targets + */ + private function warmCache(string $kernel, array $targets): void + { + $code = + 'require ' . var_export(dirname(__DIR__, 4) . '/vendor/autoload.php', true) . '; ' . $kernel . '::init();'; + foreach ($targets as $target) { + $code .= 'new ' . $target . '();'; + } + $pipes = []; + $process = proc_open([PHP_BINARY, '-r', $code], [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes); + static::assertIsResource($process); + $stdout = $pipes[1] ?? null; + $stderr = $pipes[2] ?? null; + static::assertIsResource($stdout); + static::assertIsResource($stderr); + $output = stream_get_contents($stdout); + $errors = stream_get_contents($stderr); + fclose($stdout); + fclose($stderr); + static::assertSame(0, proc_close($process), (string) $output . (string) $errors); + } + + public function testRepeatedDeclarationsKeepTheirMethodFiltersAndOrder(): void + { + $this->initialize(); + $this->assertWillBeWoven(RepeatedTarget::class); + $this->assertRepeatedDeclarations(); + } + + private function assertRepeatedDeclarations(): void + { + $target = new RepeatedTarget(); + $runtime = new RuntimeException('runtime'); + $logic = new LogicException('logic'); + $this->assertFailureEvents($runtime, static fn() => $target->first($runtime), ['middle', 'scoped']); + $this->assertFailureEvents($logic, static fn() => $target->first($logic), ['middle']); + $this->assertFailureEvents($runtime, static fn() => $target->second($runtime), ['middle']); + $this->assertFailureEvents($logic, static fn() => $target->second($logic), ['scoped', 'middle']); + $this->assertFailureEvents($runtime, static fn() => $target->ordered($runtime), ['middle', 'ordered']); + $this->assertFailureEvents($logic, static fn() => $target->ordered($logic), ['ordered', 'middle']); + } + + /** @param list $events */ + private function assertFailureEvents(Throwable $throwable, callable $call, array $events): void + { + State::$events = []; + $this->assertThrownSame($throwable, $call); + static::assertSame($events, State::$events); + } + + private function assertThrownSame(Throwable $expected, callable $call): void + { + try { + $call(); + } catch (Throwable $actual) { + static::assertSame($expected, $actual); + return; + } + static::fail('Expected the same throwable to propagate.'); + } +} diff --git a/tests/Functional/AdviceBehavior/AfterThrowing/ClassTarget.php b/tests/Functional/AdviceBehavior/AfterThrowing/ClassTarget.php new file mode 100644 index 0000000..e8fdcdd --- /dev/null +++ b/tests/Functional/AdviceBehavior/AfterThrowing/ClassTarget.php @@ -0,0 +1,14 @@ + */ + protected array $aspects = []; +} diff --git a/tests/Functional/AdviceBehavior/AfterThrowing/FailureAspect.php b/tests/Functional/AdviceBehavior/AfterThrowing/FailureAspect.php new file mode 100644 index 0000000..539ec78 --- /dev/null +++ b/tests/Functional/AdviceBehavior/AfterThrowing/FailureAspect.php @@ -0,0 +1,81 @@ +getArgument('mode') === 'before') { + throw new RuntimeException('before'); + } + $invocation->setArgument('label', 'updated'); + } + + #[Around(class: Target::class, method: 'run')] + public function around(AroundMethodInvocation $invocation): void + { + /** @var mixed $mode */ + $mode = $invocation->getArgument('mode'); + if ($mode === 'around') { + throw new RuntimeException('around'); + } + if ($mode === 'short') { + $invocation->setResult('short'); + return; + } + if ($mode === 'recover' || $mode === 'retry') { + try { + $invocation->proceed(); + } catch (Throwable) { + State::$events[] = 'caught'; + if ($mode === 'retry') { + $invocation->proceed(true); + return; + } + $invocation->setResult('recovered'); + } + } + } + + #[After(class: Target::class, method: 'run')] + public function after(AfterMethodInvocation $invocation): void + { + State::$events[] = 'after'; + if ($invocation->getArgument('mode') === 'after') { + throw new RuntimeException('after'); + } + } +} diff --git a/tests/Functional/AdviceBehavior/AfterThrowing/FilteredAspect.php b/tests/Functional/AdviceBehavior/AfterThrowing/FilteredAspect.php new file mode 100644 index 0000000..a0d247b --- /dev/null +++ b/tests/Functional/AdviceBehavior/AfterThrowing/FilteredAspect.php @@ -0,0 +1,47 @@ + */ + protected array $aspects = [FailureAspect::class, FilteredAspect::class, RepeatedAspect::class]; +} diff --git a/tests/Functional/AdviceBehavior/AfterThrowing/MethodTarget.php b/tests/Functional/AdviceBehavior/AfterThrowing/MethodTarget.php new file mode 100644 index 0000000..f32dcf2 --- /dev/null +++ b/tests/Functional/AdviceBehavior/AfterThrowing/MethodTarget.php @@ -0,0 +1,14 @@ + */ + public static array $events = []; + + /** @var list */ + public static array $invocations = []; + + public static ?Throwable $observerFailure = null; +} diff --git a/tests/Functional/AdviceBehavior/AfterThrowing/Target.php b/tests/Functional/AdviceBehavior/AfterThrowing/Target.php new file mode 100644 index 0000000..cac6a86 --- /dev/null +++ b/tests/Functional/AdviceBehavior/AfterThrowing/Target.php @@ -0,0 +1,32 @@ +exception); + } + + public function testFilteringPreservesOtherAdviceOptions(): void + { + $class = new Regex('~^App\\\\Service$~'); + $method = new Regex('~^run$~'); + $advice = new AfterThrowing($class, $method, 10, false, true, RuntimeException::class); + static::assertSame($class, $advice->class); + static::assertSame($method, $advice->method); + static::assertSame(10, $advice->order); + static::assertFalse($advice->interceptTraitMethods); + static::assertTrue($advice->onlyPublicMethods); + static::assertSame(RuntimeException::class, $advice->exception); + } + + /** @return list */ + public static function invalidFilters(): array + { + return [ + [''], + ['MissingThrowableType'], + [stdClass::class], + ['Runtime*'], + ]; + } + + #[DataProvider('invalidFilters')] + public function testInvalidFilterIsRejected(string $filter): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid exception filter "' . $filter . '"'); + new AfterThrowing(exception: $filter); + } +}