-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathCacheInterceptor.php
More file actions
75 lines (62 loc) · 1.88 KB
/
CacheInterceptor.php
File metadata and controls
75 lines (62 loc) · 1.88 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
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
declare(strict_types=1);
namespace BEAR\QueryRepository;
use BEAR\QueryRepository\Exception\LogicException;
use BEAR\Resource\ResourceObject;
use Override;
use Ray\Aop\MethodInterceptor;
use Ray\Aop\MethodInvocation;
use Throwable;
use function assert;
use function sprintf;
use function trigger_error;
use const E_USER_WARNING;
final readonly class CacheInterceptor implements MethodInterceptor
{
public function __construct(
private QueryRepositoryInterface $repository,
) {
}
/**
* {@inheritDoc}
*/
#[Override]
public function invoke(MethodInvocation $invocation)
{
$ro = $invocation->getThis();
assert($ro instanceof ResourceObject);
try {
$state = $this->repository->get($ro->uri);
} catch (Throwable $e) {
$this->triggerWarning($e);
return $invocation->proceed(); // @codeCoverageIgnore
}
if ($state instanceof ResourceState) {
$state->visit($ro);
return $ro;
}
/** @psalm-suppress MixedAssignment */
$ro = $invocation->proceed();
assert($ro instanceof ResourceObject);
try {
$ro->code === 200 ? $this->repository->put($ro) : $this->repository->purge($ro->uri);
} catch (LogicException $e) {
throw $e;
} catch (Throwable $e) { // @codeCoverageIgnore
$this->triggerWarning($e); // @codeCoverageIgnore
}
return $ro;
}
/**
* Trigger warning
*
* When the cache server is down, it will issue a warning rather than an exception to continue service.
*
* @codeCoverageIgnore
*/
private function triggerWarning(Throwable $e): void
{
$message = sprintf('%s: %s in %s:%s', $e::class, $e->getMessage(), $e->getFile(), $e->getLine());
trigger_error($message, E_USER_WARNING);
}
}