Completed
Pull Request — 1.x (#31)
by Akihito
06:34
created

CacheInterceptor   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 87.5%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 4
c 2
b 0
f 1
lcom 1
cbo 4
dl 0
loc 45
ccs 14
cts 16
cp 0.875
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A invoke() 0 21 3
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 Ray\Aop\MethodInterceptor;
12
use Ray\Aop\MethodInvocation;
13
14
class CacheInterceptor implements MethodInterceptor
15
{
16
    /**
17
     * @var QueryRepositoryInterface
18
     */
19
    private $repository;
20
21
    /**
22
     * @var EtagSetterInterface
23
     */
24
    private $setEtag;
25
26 13
    public function __construct(
27
        QueryRepositoryInterface $repository,
28
        EtagSetterInterface $setEtag
29
    ) {
30 13
        $this->repository = $repository;
31 13
        $this->setEtag = $setEtag;
32 13
    }
33
34
    /**
35
     * {@inheritdoc}
36
     */
37 11
    public function invoke(MethodInvocation $invocation)
38
    {
39 11
        $resourceObject = $invocation->getThis();
40
        /* @var $resourceObject ResourceObject */
41 11
        $stored = $this->repository->get($resourceObject->uri);
42 11
        if ($stored) {
43 7
            list($resourceObject->code, $resourceObject->headers, $resourceObject->body, $resourceObject->view) = $stored;
44
45 7
            return $resourceObject;
46
        }
47
        /* @var $cacheable Cacheable */
48
        try {
49 11
            $resourceObject = $invocation->proceed();
50 11
            $this->setEtag->__invoke($resourceObject);
51 11
            $this->repository->put($resourceObject);
52
        } catch (\Exception $e) {
53
            $this->repository->purge($resourceObject->uri);
54
        }
55
56 11
        return $resourceObject;
57
    }
58
}
59