Passed
Pull Request — 1.x (#166)
by Akihito
03:05 queued 01:47
created

CommandInterceptor   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 32
rs 10
ccs 9
cts 9
cp 1
wmc 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\QueryRepository;
6
7
use BEAR\QueryRepository\Exception\ReturnValueIsNotResourceObjectException;
8
use BEAR\RepositoryModule\Annotation\Commands;
9
use BEAR\Resource\Code;
10
use BEAR\Resource\ResourceObject;
11
use Override;
12
use Ray\Aop\MethodInterceptor;
13
use Ray\Aop\MethodInvocation;
14
15
/**
16
 * Interceptor for cache invalidation on CQRS commands with #[Purge] or #[Refresh]
17
 *
18
 * Bound to command methods (onPut/onPatch/onDelete) of #[Cacheable] classes.
19
 * Executes cache invalidation after successful write operations.
20
 *
21
 * @see \BEAR\RepositoryModule\Annotation\Purge
22
 * @see \BEAR\RepositoryModule\Annotation\Refresh
23
 * @see https://bearsunday.github.io/manuals/1.0/en/cache.html#tag-based-cache-invalidation
24
 */
25
final readonly class CommandInterceptor implements MethodInterceptor
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_READONLY, expecting T_CLASS on line 25 at column 6
Loading history...
26 13
{
27
    /** @param CommandInterface[] $commands */
28 13
    public function __construct(
29 13
        #[Commands]
30
        private array $commands,
31
    ) {
32
    }
33
34
    /**
35
     * {@inheritDoc}
36 10
     *
37
     * @throws ReturnValueIsNotResourceObjectException
38 10
     */
39 10
    #[Override]
40 1
    public function invoke(MethodInvocation $invocation)
41
    {
42
        /** @psalm-suppress MixedAssignment */
43 9
        $ro = $invocation->proceed();
44 2
        if (! $ro instanceof ResourceObject) {
45
            throw new ReturnValueIsNotResourceObjectException($invocation->getThis()::class);
46
        }
47 8
48 8
        if ($ro->code >= Code::BAD_REQUEST) {
49
            return $ro;
50
        }
51 7
52
        foreach ($this->commands as $command) {
53
            $command->command($invocation, $ro);
54
        }
55
56
        return $ro;
57
    }
58
}
59