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
49 changes: 45 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down
20 changes: 19 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 0 additions & 1 deletion src/Advice/AdviceType.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
44 changes: 44 additions & 0 deletions src/Attributes/AfterThrowing.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace Okapi\Aop\Attributes;

use Attribute;
use InvalidArgumentException;
use Okapi\Aop\Core\Attributes\AdviceType\MethodAdvice;
use Okapi\Wildcards\Regex;
use Throwable;

/**
* Run advice when the target method throws.
*/
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class AfterThrowing extends MethodAdvice
{
/**
* @var class-string<Throwable>
*/
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;
}
}
2 changes: 2 additions & 0 deletions src/Core/Attributes/AdviceType/MethodAdvice.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -17,6 +18,7 @@
* @see Before
* @see Around
* @see After
* @see AfterThrowing
*/
abstract class MethodAdvice extends BaseAdvice
{
Expand Down
5 changes: 4 additions & 1 deletion src/Core/Cache/CacheStateManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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;
}
Expand Down
3 changes: 3 additions & 0 deletions src/Core/Container/AdviceContainerFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class AdviceContainerFactory
* @param BaseReflectionClass $aspectRefClass
* @param BaseReflectionAttribute $adviceAttribute
* @param BaseReflectionMethod $adviceRefMethod
* @param int $declarationIndex
*
* @return AdviceContainer
*
Expand All @@ -38,6 +39,7 @@ public function createAdviceContainer(
BaseReflectionClass $aspectRefClass,
BaseReflectionAttribute $adviceAttribute,
BaseReflectionMethod $adviceRefMethod,
int $declarationIndex = 0,
): AdviceContainer {
// Instantiate the advice attribute
$adviceAttributeInstance = $adviceAttribute->newInstance();
Expand All @@ -54,6 +56,7 @@ public function createAdviceContainer(
'adviceAttributeInstance' => $adviceAttributeInstance,
'adviceRefMethod' => $adviceRefMethod,
'isExplicit' => $isExplicit,
'declarationIndex' => $declarationIndex,
]);

// If the aspect is implicit,
Expand Down
6 changes: 4 additions & 2 deletions src/Core/Container/AdviceType/MethodAdviceContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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;
}

/**
Expand Down
3 changes: 2 additions & 1 deletion src/Core/Container/AspectManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
22 changes: 19 additions & 3 deletions src/Core/Factory/InvocationFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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, [
Expand Down Expand Up @@ -72,6 +88,6 @@ public function getInvocation(
'arguments' => &$arguments,
]);
}
throw new \LogicException('Unsupported advice type.');
throw new LogicException('Unsupported advice type.');
}
}
Loading
Loading