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
|
|
|
|
13
|
|
|
class CacheInterceptor implements MethodInterceptor |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var QueryRepositoryInterface |
17
|
|
|
*/ |
18
|
|
|
private $repository; |
19
|
|
|
|
20
|
|
|
public function __construct( |
21
|
|
|
QueryRepositoryInterface $repository |
22
|
|
|
) { |
23
|
|
|
$this->repository = $repository; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* {@inheritdoc} |
28
|
|
|
*/ |
29
|
|
|
public function invoke(MethodInvocation $invocation) |
30
|
|
|
{ |
31
|
|
|
/** @var ResourceObject $ro */ |
32
|
|
|
$ro = $invocation->getThis(); |
33
|
|
|
try { |
34
|
|
|
$stored = $this->repository->get($ro->uri); |
35
|
|
|
} catch (LogicException | RuntimeException $e) { |
36
|
|
|
throw $e; |
37
|
|
|
} catch (\Exception $e) { |
38
|
|
|
$this->triggerError($e); |
39
|
|
|
|
40
|
|
|
return $invocation->proceed(); |
41
|
|
|
} |
42
|
|
|
if ($stored) { |
43
|
|
|
[$ro->uri, $ro->code, $ro->headers, $ro->body, $ro->view] = $stored; |
44
|
|
|
|
45
|
|
|
return $ro; |
46
|
|
|
} |
47
|
|
|
$ro = $invocation->proceed(); |
48
|
|
|
try { |
49
|
|
|
$ro->code === 200 ? $this->repository->put($ro) : $this->repository->purge($ro->uri); |
50
|
|
|
} catch (LogicException | RuntimeException $e) { |
51
|
|
|
throw $e; |
52
|
|
|
} catch (\Exception $e) { |
53
|
|
|
$this->triggerError($e); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return $ro; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Trigger error when cache server is down instead of throwing the exception |
61
|
|
|
*/ |
62
|
|
|
private function triggerError(\Exception $e) : void |
63
|
|
|
{ |
64
|
|
|
$message = sprintf('%s: %s in %s:%s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()); |
65
|
|
|
trigger_error($message, E_USER_WARNING); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|