-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathCommandInterceptor.php
More file actions
62 lines (54 loc) · 1.78 KB
/
CommandInterceptor.php
File metadata and controls
62 lines (54 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
declare(strict_types=1);
namespace BEAR\QueryRepository;
use BEAR\QueryRepository\Exception\ReturnValueIsNotResourceObjectException;
use BEAR\RepositoryModule\Annotation\Commands;
use BEAR\Resource\Code;
use BEAR\Resource\ResourceObject;
use Override;
use Ray\Aop\MethodInterceptor;
use Ray\Aop\MethodInvocation;
/**
* Interceptor for cache invalidation on CQRS commands with #[Purge] or #[Refresh]
*
* Automatically bound to all command methods (onPut/onPatch/onDelete) of #[Cacheable] classes.
* Processes #[Purge] and #[Refresh] annotations on these methods and executes cache
* invalidation after successful write operations.
*
* For non-Cacheable classes, use RefreshInterceptor instead by explicitly marking methods
* with #[Purge] or #[Refresh].
*
* @see \BEAR\RepositoryModule\Annotation\Purge
* @see \BEAR\RepositoryModule\Annotation\Refresh
* @see https://bearsunday.github.io/manuals/1.0/en/cache.html#tag-based-cache-invalidation
*/
final readonly class CommandInterceptor implements MethodInterceptor
{
/** @param CommandInterface[] $commands */
public function __construct(
#[Commands]
private array $commands,
) {
}
/**
* {@inheritDoc}
*
* @throws ReturnValueIsNotResourceObjectException
*/
#[Override]
public function invoke(MethodInvocation $invocation)
{
/** @psalm-suppress MixedAssignment */
$ro = $invocation->proceed();
if (! $ro instanceof ResourceObject) {
throw new ReturnValueIsNotResourceObjectException($invocation->getThis()::class);
}
if ($ro->code >= Code::BAD_REQUEST) {
return $ro;
}
foreach ($this->commands as $command) {
$command->command($invocation, $ro);
}
return $ro;
}
}