Skip to content

Commit 0fe8784

Browse files
authored
feat(advice): add filtered AfterThrowing advice (#99)
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.
1 parent 030c9fd commit 0fe8784

29 files changed

Lines changed: 930 additions & 28 deletions

‎README.md‎

Lines changed: 45 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ composer require okapi/aop
116116
target classes. Aspects must be annotated with the `#[Aspect]` attribute.
117117

118118
- **Advice**: The logic that you want to apply to your target classes. Advice
119-
methods must be annotated with the `#[Before]`, `#[Around]` or `#[After]`
119+
methods must be annotated with `#[Before]`, `#[Around]`, `#[After]`, or `#[AfterThrowing]`
120120
attributes.
121121

122122
- **Join Point**: A point in the execution of your target classes where you can
@@ -182,7 +182,7 @@ use Okapi\Aop\Invocation\AfterMethodInvocation;
182182
class DiscountAspect
183183
{
184184
// Annotate the methods that you want to intercept with
185-
// "Before", "Around" or "After" attributes
185+
// "Before", "Around", "After", or "AfterThrowing" attributes
186186
#[After(
187187
// Use named arguments
188188
// You can also use Wildcards (see Okapi/Wildcards package)
@@ -307,6 +307,47 @@ class PaymentProcessorAspect
307307
```
308308

309309

310+
### AfterThrowing advice
311+
312+
`#[AfterThrowing]` runs when the intercepted target method throws an exception or
313+
PHP error (`Throwable`). It receives the original throwable and the invocation
314+
context:
315+
316+
```php
317+
use Okapi\Aop\Attributes\AfterThrowing;
318+
use Okapi\Aop\Invocation\AfterThrowingMethodInvocation;
319+
320+
// Inside an aspect:
321+
#[AfterThrowing(
322+
class: PaymentProcessor::class,
323+
method: 'processPayment',
324+
exception: \DomainException::class,
325+
)]
326+
public function logFailure(AfterThrowingMethodInvocation $invocation): void
327+
{
328+
error_log($invocation->getThrowable()->getMessage());
329+
}
330+
```
331+
332+
It supports the same class/method patterns, `order`, `interceptTraitMethods`, and
333+
`onlyPublicMethods` options as the other method advice types, including explicit
334+
class-level and method-level aspects. Advice runs in ascending `order`.
335+
336+
The optional `exception` filter matches the given type and its subclasses. It
337+
defaults to `Throwable::class`, which includes exceptions and PHP errors. Use
338+
`Exception::class` to exclude errors, or `Error::class` to handle only errors.
339+
An unknown type or a type that does not implement `Throwable` is rejected when the
340+
advice attribute is instantiated.
341+
342+
- Successful calls and exceptions caught inside the target do not trigger it.
343+
- The original throwable is rethrown after the advice completes. Return values are
344+
ignored; the invocation has no `proceed()` or `setResult()` method.
345+
- It runs before an outer `Around` advice catches a target failure. Repeated target
346+
calls through `proceed(true)` trigger it for each failure.
347+
- Exceptions originating in `Before`, `Around`, or `After` advice do not trigger it.
348+
- If an `AfterThrowing` advice throws, that new throwable propagates and remaining
349+
`AfterThrowing` advice is skipped.
350+
310351
### Regular-expression patterns
311352

312353
`class` and `method` accept either wildcard strings or explicit
@@ -324,7 +365,7 @@ use Okapi\Wildcards\Regex;
324365

325366
This matches controller methods whose names start with a letter, excluding
326367
constructors and other magic methods. Regex objects can also be used for `class`.
327-
The same arguments are supported by `Before`, `Around`, and `After`.
368+
The same arguments are supported by `Before`, `Around`, `After`, and `AfterThrowing`.
328369

329370
Pass a complete PHP regular expression, including delimiters and any modifiers.
330371
Regex patterns are used as written: add `^` and `$` when you want to match the
@@ -709,7 +750,7 @@ $firstLog = $logs[0];
709750

710751
# Features
711752

712-
- **Advice types:** "Before", "Around" and "After"
753+
- **Advice types:** "Before", "Around", "After", and "AfterThrowing"
713754

714755
- Intercept "private" and "protected" methods
715756
(Will show errors in IDEs)

‎docs/architecture.md‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,25 @@ flowchart TD
125125

126126
This is the normal successful path. An exception interrupts it; `After` is not a
127127
`finally` handler. Missing advice groups are skipped. The configured advice order
128-
is applied within the Before, Around, and After groups.
128+
is applied within the Before, Around, After, and AfterThrowing groups.
129+
130+
If an original target call throws a `Throwable`, the interceptor runs the matching
131+
`AfterThrowing` advice in order and rethrows the same object. This happens inside
132+
the original-method callback, before control returns to any surrounding Around
133+
advice. Successful calls and failures originating in other advice skip this group.
134+
AfterThrowing invocations expose `getThrowable()` and invocation context, without
135+
`proceed()` or result replacement. If this advice itself throws, its throwable
136+
propagates immediately and the remaining failure advice does not run.
137+
138+
Each AfterThrowing attribute can restrict execution with an `exception` type
139+
filter. Matching includes subclasses; the default `Throwable`
140+
filter accepts both exceptions and errors. The filter is validated when the advice
141+
attribute is instantiated, and is applied again on each failing target call.
142+
143+
Join points and cached metadata identify each advice declaration by its aspect,
144+
method, and attribute index. Repeated attributes retain their own method filters
145+
and execution order. The cache hash includes the declaration format version so
146+
older method-name-only caches are rebuilt, including caches of explicit aspects.
129147

130148
An Around invocation's `proceed()` advances the chain. The original method can run
131149
inside that call; the Around advice then resumes and can modify the result. The

‎src/Advice/AdviceType.php‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,5 @@ enum AdviceType
1414
case After;
1515
// Reserved for future after-returning advice support.
1616
case AfterReturning;
17-
// Reserved for future after-throwing advice support.
1817
case AfterThrowing;
1918
}

‎src/Attributes/AfterThrowing.php‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
namespace Okapi\Aop\Attributes;
4+
5+
use Attribute;
6+
use InvalidArgumentException;
7+
use Okapi\Aop\Core\Attributes\AdviceType\MethodAdvice;
8+
use Okapi\Wildcards\Regex;
9+
use Throwable;
10+
11+
/**
12+
* Run advice when the target method throws.
13+
*/
14+
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
15+
class AfterThrowing extends MethodAdvice
16+
{
17+
/**
18+
* @var class-string<Throwable>
19+
*/
20+
public readonly string $exception;
21+
22+
/**
23+
* @param string $exception The Throwable class or interface to match,
24+
* including subclasses.
25+
*/
26+
public function __construct(
27+
string|Regex|null $class = null,
28+
string|Regex|null $method = null,
29+
int $order = 0,
30+
bool $interceptTraitMethods = true,
31+
bool $onlyPublicMethods = false,
32+
string $exception = Throwable::class,
33+
) {
34+
parent::__construct($class, $method, $order, $interceptTraitMethods, $onlyPublicMethods);
35+
36+
if (!is_a($exception, Throwable::class, true)) {
37+
throw new InvalidArgumentException(
38+
'Invalid exception filter "' . $exception . '": expected a Throwable class or interface.',
39+
);
40+
}
41+
42+
$this->exception = $exception;
43+
}
44+
}

‎src/Core/Attributes/AdviceType/MethodAdvice.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Okapi\Aop\Core\Attributes\AdviceType;
44

55
use Okapi\Aop\Attributes\After;
6+
use Okapi\Aop\Attributes\AfterThrowing;
67
use Okapi\Aop\Attributes\Around;
78
use Okapi\Aop\Attributes\Before;
89
use Okapi\Aop\Core\Attributes\Base\BaseAdvice;
@@ -17,6 +18,7 @@
1718
* @see Before
1819
* @see Around
1920
* @see After
21+
* @see AfterThrowing
2022
*/
2123
abstract class MethodAdvice extends BaseAdvice
2224
{

‎src/Core/Cache/CacheStateManager.php‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
*/
1313
class CacheStateManager extends CodeTransformerCacheStateManager
1414
{
15+
// Invalidate method-name-only join points, including caches of explicit aspects.
16+
private const ADVICE_DECLARATION_VERSION = 1;
17+
1518
// region DI
1619

1720
#[Inject]
@@ -29,7 +32,7 @@ protected function getHash(): string
2932
$transformerHash = parent::getHash();
3033

3134
$aspectAdviceNames = $this->aspectManager->getAspectAdviceNames();
32-
$aspectHash = md5(serialize($aspectAdviceNames));
35+
$aspectHash = md5(serialize([self::ADVICE_DECLARATION_VERSION, $aspectAdviceNames]));
3336

3437
return $transformerHash . $aspectHash;
3538
}

‎src/Core/Container/AdviceContainerFactory.php‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ class AdviceContainerFactory
2727
* @param BaseReflectionClass $aspectRefClass
2828
* @param BaseReflectionAttribute $adviceAttribute
2929
* @param BaseReflectionMethod $adviceRefMethod
30+
* @param int $declarationIndex
3031
*
3132
* @return AdviceContainer
3233
*
@@ -38,6 +39,7 @@ public function createAdviceContainer(
3839
BaseReflectionClass $aspectRefClass,
3940
BaseReflectionAttribute $adviceAttribute,
4041
BaseReflectionMethod $adviceRefMethod,
42+
int $declarationIndex = 0,
4143
): AdviceContainer {
4244
// Instantiate the advice attribute
4345
$adviceAttributeInstance = $adviceAttribute->newInstance();
@@ -54,6 +56,7 @@ public function createAdviceContainer(
5456
'adviceAttributeInstance' => $adviceAttributeInstance,
5557
'adviceRefMethod' => $adviceRefMethod,
5658
'isExplicit' => $isExplicit,
59+
'declarationIndex' => $declarationIndex,
5760
]);
5861

5962
// If the aspect is implicit,

‎src/Core/Container/AdviceType/MethodAdviceContainer.php‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ class MethodAdviceContainer extends AdviceContainer
3737
* @param MethodAdvice $adviceAttributeInstance
3838
* @param BaseReflectionMethod $adviceRefMethod
3939
* @param bool $isExplicit
40+
* @param int $declarationIndex Position among the advice attributes on the method.
4041
*/
4142
public function __construct(
4243
string $aspectClassName,
@@ -46,6 +47,7 @@ public function __construct(
4647
MethodAdvice $adviceAttributeInstance,
4748
public readonly BaseReflectionMethod $adviceRefMethod,
4849
private readonly bool $isExplicit,
50+
private readonly int $declarationIndex = 0,
4951
) {
5052
parent::__construct(
5153
$aspectClassName,
@@ -81,13 +83,13 @@ public function getMatchedMethods(): array
8183
}
8284

8385
/**
84-
* Get advice name.
86+
* Get the identity of this advice declaration.
8587
*
8688
* @return string
8789
*/
8890
public function getName(): string
8991
{
90-
return $this->aspectClassName . '::' . $this->adviceRefMethod->getName();
92+
return $this->aspectClassName . '::' . $this->adviceRefMethod->getName() . '#' . $this->declarationIndex;
9193
}
9294

9395
/**

‎src/Core/Container/AspectManager.php‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,13 +161,14 @@ public function loadAspect(mixed $aspectClassName): void
161161
);
162162

163163
// Create advice containers and store them
164-
foreach ($adviceAttributes as $adviceAttribute) {
164+
foreach ($adviceAttributes as $declarationIndex => $adviceAttribute) {
165165
$adviceContainer = $this->adviceContainerFactory->createAdviceContainer(
166166
$aspectClassName,
167167
$aspectInstance,
168168
$aspectRefClass,
169169
$adviceAttribute,
170170
$adviceRefMember,
171+
$declarationIndex,
171172
);
172173

173174
$this->aspectAdviceContainers[$aspectClassName][] = $adviceContainer;

‎src/Core/Factory/InvocationFactory.php‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,19 @@
22

33
namespace Okapi\Aop\Core\Factory;
44

5+
use LogicException;
56
use Okapi\Aop\Attributes\After;
7+
use Okapi\Aop\Attributes\AfterThrowing;
68
use Okapi\Aop\Attributes\Around;
79
use Okapi\Aop\Attributes\Before;
810
use Okapi\Aop\Core\Container\AdviceType\MethodAdviceContainer;
911
use Okapi\Aop\Invocation\AfterMethodInvocation;
12+
use Okapi\Aop\Invocation\AfterThrowingMethodInvocation;
1013
use Okapi\Aop\Invocation\AroundMethodInvocation;
1114
use Okapi\Aop\Invocation\BeforeMethodInvocation;
1215
use Okapi\Aop\Invocation\MethodInvocation;
1316
use Okapi\CodeTransformer\Core\DI;
17+
use Throwable;
1418

1519
/**
1620
* # Invocation Factory
@@ -28,10 +32,9 @@ class InvocationFactory
2832
* @param string $methodName
2933
* @param mixed $result
3034
* @param array $arguments
35+
* @param Throwable|null $throwable The target failure for AfterThrowing advice.
3136
*
3237
* @return MethodInvocation
33-
*
34-
* @noinspection PhpInconsistentReturnPointsInspection
3538
*/
3639
public function getInvocation(
3740
MethodAdviceContainer $adviceContainer,
@@ -40,8 +43,21 @@ public function getInvocation(
4043
string $methodName,
4144
mixed $result,
4245
array &$arguments,
46+
?Throwable $throwable = null,
4347
): MethodInvocation {
4448
switch (true) {
49+
case $adviceContainer->adviceAttributeInstance instanceof AfterThrowing:
50+
if ($throwable === null) {
51+
throw new LogicException('AfterThrowing advice requires a target throwable.');
52+
}
53+
return DI::make(AfterThrowingMethodInvocation::class, [
54+
'subject' => $subject,
55+
'className' => $className,
56+
'methodName' => $methodName,
57+
'arguments' => &$arguments,
58+
'throwable' => $throwable,
59+
]);
60+
4561
// Before
4662
case $adviceContainer->adviceAttributeInstance instanceof Before:
4763
return DI::make(BeforeMethodInvocation::class, [
@@ -72,6 +88,6 @@ public function getInvocation(
7288
'arguments' => &$arguments,
7389
]);
7490
}
75-
throw new \LogicException('Unsupported advice type.');
91+
throw new LogicException('Unsupported advice type.');
7692
}
7793
}

0 commit comments

Comments
 (0)