Completed
Pull Request — 1.x (#53)
by Akihito
04:27
created

CacheInterceptor   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 0
loc 46
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A invoke() 0 22 4
A __construct() 0 7 1
1
<?php
2
/**
3
 * This file is part of the BEAR.QueryRepository package.
4
 *
5
 * @license http://opensource.org/licenses/MIT MIT
6
 */
7
namespace BEAR\QueryRepository;
8
9
use BEAR\RepositoryModule\Annotation\Cacheable;
10
use BEAR\Resource\ResourceObject;
11
use Doctrine\Common\Annotations\Reader;
12
use Ray\Aop\MethodInterceptor;
13
use Ray\Aop\MethodInvocation;
14
15
class CacheInterceptor implements MethodInterceptor
16
{
17
    /**
18
     * @var QueryRepositoryInterface
19
     */
20
    private $repository;
21
22
    /**
23
     * @var Reader
24
     */
25
    private $reader;
26
27 20
    public function __construct(
28
        QueryRepositoryInterface $repository,
29
        Reader $annotationReader
30
    ) {
31 20
        $this->repository = $repository;
32 20
        $this->reader = $annotationReader;
33 20
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 18
    public function invoke(MethodInvocation $invocation)
39
    {
40
        /** @var ResourceObject $ro */
41 18
        $ro = $invocation->getThis();
42 18
        $stored = $this->repository->get($ro->uri);
43 18
        if ($stored) {
44 11
            list($ro->uri, $ro->code, $ro->headers, $ro->body, $ro->view) = $stored;
45
46 11
            return $ro;
47
        }
48
        /* @var $cacheable Cacheable */
49
        try {
50
            /** @var ResourceObject $ro */
51 18
            $ro = $invocation->proceed();
52 18
            $ro->code === 200 ? $this->repository->put($ro) : $this->repository->purge($ro->uri);
53 1
        } catch (\Exception $e) {
54 1
            $this->repository->purge($ro->uri);
55 1
            throw $e;
56
        }
57
58 17
        return $ro;
59
    }
60
}
61