Completed
Pull Request — 1.x (#58)
by Akihito
15:42
created

CacheInterceptor::invoke()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5.009

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 13
cts 14
cp 0.9286
rs 9.2248
c 0
b 0
f 0
cc 5
nc 7
nop 1
crap 5.009
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\QueryRepository;
6
7
use BEAR\QueryRepository\Exception\ReturnValueIsNotResourceObjectException;
8
use BEAR\Resource\ResourceObject;
9
use Ray\Aop\MethodInterceptor;
10
use Ray\Aop\MethodInvocation;
11
use function get_class;
12
13
class CacheInterceptor implements MethodInterceptor
14
{
15
    /**
16
     * @var QueryRepositoryInterface
17
     */
18
    private $repository;
19
20 21
    public function __construct(
21
        QueryRepositoryInterface $repository
22
    ) {
23 21
        $this->repository = $repository;
24 21
    }
25
26
    /**
27
     * {@inheritdoc}
28
     */
29 19
    public function invoke(MethodInvocation $invocation)
30
    {
31 19
        $ro = $invocation->getThis();
32 19
        if (! $ro instanceof ResourceObject) {
33
            throw new ReturnValueIsNotResourceObjectException(get_class($ro));
34
        }
35 19
        $stored = $this->repository->get($ro->uri);
36 19
        if ($stored) {
37 11
            list($ro->uri, $ro->code, $ro->headers, $ro->body, $ro->view) = $stored;
38
39 11
            return $ro;
40
        }
41
42
        try {
43 19
            $ro = $invocation->proceed();
44 19
            $ro->code === 200 ? $this->repository->put($ro) : $this->repository->purge($ro->uri);
45 1
        } catch (\Exception $e) {
46 1
            $this->repository->purge($ro->uri);
47
48 1
            throw $e;
49
        }
50
51 18
        return $ro;
52
    }
53
}
54