1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace BEAR\QueryRepository; |
6
|
|
|
|
7
|
|
|
use BEAR\QueryRepository\Exception\LogicException; |
8
|
|
|
use BEAR\QueryRepository\Exception\RuntimeException; |
9
|
|
|
use BEAR\Resource\ResourceObject; |
10
|
|
|
use Ray\Aop\MethodInterceptor; |
11
|
|
|
use Ray\Aop\MethodInvocation; |
12
|
|
|
use Throwable; |
13
|
|
|
|
14
|
|
|
use function assert; |
15
|
|
|
use function get_class; |
16
|
|
|
use function sprintf; |
17
|
|
|
use function trigger_error; |
18
|
|
|
|
19
|
|
|
use const E_USER_WARNING; |
20
|
|
|
|
21
|
|
|
class CacheInterceptor implements MethodInterceptor |
22
|
|
|
{ |
23
|
|
|
/** @var QueryRepositoryInterface */ |
24
|
|
|
private $repository; |
25
|
|
|
|
26
|
|
|
public function __construct( |
27
|
|
|
QueryRepositoryInterface $repository |
28
|
|
|
) { |
29
|
|
|
$this->repository = $repository; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* {@inheritdoc} |
34
|
|
|
*/ |
35
|
|
|
public function invoke(MethodInvocation $invocation) |
36
|
|
|
{ |
37
|
|
|
$ro = $invocation->getThis(); |
38
|
|
|
assert($ro instanceof ResourceObject); |
39
|
|
|
try { |
40
|
|
|
$stored = $this->repository->get($ro->uri); |
41
|
|
|
} catch (LogicException $e) { |
42
|
|
|
throw $e; |
43
|
|
|
} catch (Throwable $e) { |
44
|
|
|
$this->triggerWarning($e); |
45
|
|
|
|
46
|
|
|
return $invocation->proceed(); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
if ($stored) { |
50
|
|
|
[$ro->uri, $ro->code, $ro->headers, $ro->body, $ro->view] = $stored; |
51
|
|
|
|
52
|
|
|
return $ro; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** @psalm-suppress MixedAssignment */ |
56
|
|
|
$ro = $invocation->proceed(); |
57
|
|
|
assert($ro instanceof ResourceObject); |
58
|
|
|
try { |
59
|
|
|
$ro->code === 200 ? $this->repository->put($ro) : $this->repository->purge($ro->uri); |
60
|
|
|
} catch (LogicException $e) { |
61
|
|
|
throw $e; |
62
|
|
|
} catch (Throwable $e) { |
63
|
|
|
$this->triggerWarning($e); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $ro; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Trigger warning |
71
|
|
|
* |
72
|
|
|
* When the cache server is down, it will issue a warning rather than an exception to continue service. |
73
|
|
|
*/ |
74
|
|
|
private function triggerWarning(Throwable $e): void |
75
|
|
|
{ |
76
|
|
|
$message = sprintf('%s: %s in %s:%s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()); |
77
|
|
|
trigger_error($message, E_USER_WARNING); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|