Completed
Push — 1.x ( ceb55c...e57da8 )
by Akihito
15s queued 13s
created

CacheInterceptor::invoke()   B

Complexity

Conditions 7
Paths 11

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 11
cts 11
cp 1
rs 8.5226
c 0
b 0
f 0
cc 7
nc 11
nop 1
crap 7
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->errorLog($e);
39 22
40 22
            return $invocation->proceed();
41 1
        }
42 1
        if ($stored) {
43
            list($ro->uri, $ro->code, $ro->headers, $ro->body, $ro->view) = $stored;
44 1
45
            return $ro;
46
        }
47 21
        try {
48
            $ro = $invocation->proceed();
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->errorLog($e);
54
        }
55
56
        return $ro;
57
    }
58
59
    private function errorLog(\Exception $e) : void
60
    {
61
        $message = sprintf('%s: %s in %s:%s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine());
62
        syslog(LOG_CRIT, $message);
63
    }
64
}
65