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

CacheInterceptor   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 94.12%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 4
dl 0
loc 41
ccs 16
cts 17
cp 0.9412
rs 10
c 0
b 0
f 0

2 Methods

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