Completed
Push — 1.x ( d9c05b...5604d5 )
by Akihito
21s queued 12s
created

CacheInterceptor::triggerError()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
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 24
    private $repository;
19
20
    public function __construct(
21 24
        QueryRepositoryInterface $repository
22 24
    ) {
23
        $this->repository = $repository;
24
    }
25
26
    /**
27 22
     * {@inheritdoc}
28
     */
29
    public function invoke(MethodInvocation $invocation)
30 22
    {
31 22
        /** @var ResourceObject $ro */
32 22
        $ro = $invocation->getThis();
33 12
        try {
34
            $stored = $this->repository->get($ro->uri);
35 12
        } catch (LogicException | RuntimeException $e) {
36
            throw $e;
37
        } catch (\Exception $e) {
38
            $this->triggerError($e);
39 22
40 22
            return $invocation->proceed();
41 1
        }
42 1
        if ($stored) {
43
            [$ro->uri, $ro->code, $ro->headers, $ro->body, $ro->view] = $stored;
44 1
45
            return $ro;
46
        }
47 21
        $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