-
Notifications
You must be signed in to change notification settings - Fork 9
/
CacheInterceptor.php
78 lines (64 loc) · 1.94 KB
/
CacheInterceptor.php
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
76
77
78
<?php
declare(strict_types=1);
namespace BEAR\QueryRepository;
use BEAR\QueryRepository\Exception\LogicException;
use BEAR\Resource\ResourceObject;
use Ray\Aop\MethodInterceptor;
use Ray\Aop\MethodInvocation;
use Throwable;
use function assert;
use function get_class;
use function sprintf;
use function trigger_error;
use const E_USER_WARNING;
class CacheInterceptor implements MethodInterceptor
{
/** @var QueryRepositoryInterface */
private $repository;
public function __construct(
QueryRepositoryInterface $repository
) {
$this->repository = $repository;
}
/**
* {@inheritdoc}
*/
public function invoke(MethodInvocation $invocation)
{
$ro = $invocation->getThis();
assert($ro instanceof ResourceObject);
try {
$stored = $this->repository->get($ro->uri);
} catch (LogicException $e) {
throw $e;
} catch (Throwable $e) {
$this->triggerWarning($e);
return $invocation->proceed();
}
if ($stored) {
[$ro->uri, $ro->code, $ro->headers, $ro->body, $ro->view] = $stored;
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) {
$this->triggerWarning($e);
}
return $ro;
}
/**
* Trigger warning
*
* When the cache server is down, it will issue a warning rather than an exception to continue service.
*/
private function triggerWarning(Throwable $e): void
{
$message = sprintf('%s: %s in %s:%s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine());
trigger_error($message, E_USER_WARNING);
}
}