Completed
Push — hotfix-hide-exception ( f93e47 )
by Akihito
01:56
created

CacheInterceptor   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 2
dl 0
loc 55
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B invoke() 0 29 7
A triggerError() 0 5 1
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