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