Completed
Push — 1.x ( 82effb...ab39dc )
by Akihito
19s
created

QueryRepository   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 172
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 95.52%

Importance

Changes 0
Metric Value
wmc 27
lcom 1
cbo 4
dl 0
loc 172
ccs 64
cts 67
cp 0.9552
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 11 2
A purge() 0 6 1
A getHttpCacheAnnotation() 0 8 3
A getCacheableAnnotation() 0 8 3
A evaluateBody() 0 13 4
A getExpiryTime() 0 12 4
A getExpiryAtSec() 0 10 2
A setMaxAge() 0 10 2
A __construct() 0 11 1
A put() 0 24 5
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\QueryRepository\Exception\ExpireAtKeyNotExists;
10
use BEAR\RepositoryModule\Annotation\Cacheable;
11
use BEAR\RepositoryModule\Annotation\HttpCache;
12
use BEAR\RepositoryModule\Annotation\Storage;
13
use BEAR\Resource\AbstractUri;
14
use BEAR\Resource\RequestInterface;
15
use BEAR\Resource\ResourceObject;
16
use Doctrine\Common\Annotations\Reader;
17
18
class QueryRepository implements QueryRepositoryInterface
19
{
20
    const ETAG_BY_URI = 'etag-by-uri';
21
22
    /**
23
     * @var ResourceStorageInterface
24
     */
25
    private $storage;
26
27
    /**
28
     * @var Reader
29
     */
30
    private $reader;
31
32
    /**
33
     * @var Expiry
34
     */
35
    private $expiry;
36
37
    /**
38
     * @var EtagSetterInterface
39
     */
40
    private $setEtag;
41
42
    /**
43
     * @Storage("kvs")
44
     */
45 26
    public function __construct(
46
        EtagSetterInterface $setEtag,
47
        ResourceStorageInterface $storage,
48
        Reader $reader,
49
        Expiry $expiry
50
    ) {
51 26
        $this->setEtag = $setEtag;
52 26
        $this->reader = $reader;
53 26
        $this->storage = $storage;
54 26
        $this->expiry = $expiry;
55 26
    }
56
57
    /**
58
     * {@inheritdoc}
59
     *
60
     * @throws \ReflectionException
61
     */
62 24
    public function put(ResourceObject $ro)
63
    {
64 24
        $ro->toString();
65 24
        $httpCache = $this->getHttpCacheAnnotation($ro);
66 24
        $cacheable = $this->getCacheableAnnotation($ro);
67
        /* @var Cacheable $cacheable|null */
68 24
        ($this->setEtag)($ro, null, $httpCache);
69 24
        if (isset($ro->headers['ETag'])) {
70 24
            $this->storage->updateEtag($ro);
71
        }
72 24
        $body = $this->evaluateBody($ro->body);
0 ignored issues
show
Unused Code introduced by
$body is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
73 24
        $lifeTime = $this->getExpiryTime($ro, $cacheable);
74 23
        $this->setMaxAge($ro, $lifeTime);
75 23
        if ($cacheable instanceof Cacheable && $cacheable->type === 'view') {
0 ignored issues
show
Bug introduced by
The class BEAR\RepositoryModule\Annotation\Cacheable does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
76 2
            if (! $ro->view) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ro->view of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
77
                // render
78
                $ro->view = $ro->toString();
79
            }
80
81 2
            return $this->storage->saveView($ro, $lifeTime);
82
        }
83
        // "value" cache type
84 21
        return $this->storage->saveValue($ro, $lifeTime);
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90 22
    public function get(AbstractUri $uri)
91
    {
92 22
        $data = $this->storage->get($uri);
93 22
        if ($data === false) {
94 20
            return false;
95
        }
96 14
        $age = \time() - \strtotime($data[2]['Last-Modified']);
97 14
        $data[2]['Age'] = $age;
98
99 14
        return $data;
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105 12
    public function purge(AbstractUri $uri)
106
    {
107 12
        $this->storage->deleteEtag($uri);
108
109 12
        return $this->storage->delete($uri);
110
    }
111
112
    /**
113
     * @throws \ReflectionException
114
     */
115 24
    private function getHttpCacheAnnotation(ResourceObject $ro)
116
    {
117 24
        $annotation = $this->reader->getClassAnnotation(new \ReflectionClass($ro), HttpCache::class);
118 24
        if ($annotation instanceof HttpCache || $annotation === null) {
0 ignored issues
show
Bug introduced by
The class BEAR\RepositoryModule\Annotation\HttpCache does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
119 24
            return $annotation;
120
        }
121
        throw new \LogicException();
122
    }
123
124
    /**
125
     * @throws \ReflectionException
126
     */
127 24
    private function getCacheableAnnotation(ResourceObject $ro)
128
    {
129 24
        $annotation = $this->reader->getClassAnnotation(new \ReflectionClass($ro), Cacheable::class);
130 24
        if ($annotation instanceof Cacheable || $annotation === null) {
0 ignored issues
show
Bug introduced by
The class BEAR\RepositoryModule\Annotation\Cacheable does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
131 24
            return $annotation;
132
        }
133
        throw new \LogicException();
134
    }
135
136
    /**
137
     * @param mixed $body
138
     *
139
     * @return mixed
140
     */
141 24
    private function evaluateBody($body)
142
    {
143 24
        if (! \is_array($body)) {
144 7
            return $body;
145
        }
146 17
        foreach ($body as &$item) {
147 17
            if ($item instanceof RequestInterface) {
148 17
                $item = ($item)();
149
            }
150
        }
151
152 17
        return $body;
153
    }
154
155 25
    private function getExpiryTime(ResourceObject $ro, Cacheable $cacheable = null) : int
156
    {
157 25
        if ($cacheable === null) {
158 4
            return 0;
159
        }
160
161 21
        if ($cacheable->expiryAt) {
162 2
            return $this->getExpiryAtSec($ro, $cacheable);
163
        }
164
165 19
        return $cacheable->expirySecond ? $cacheable->expirySecond : $this->expiry[$cacheable->expiry];
166
    }
167
168 2
    private function getExpiryAtSec(ResourceObject $ro, Cacheable $cacheable) : int
169
    {
170 2
        if (! isset($ro->body[$cacheable->expiryAt])) {
171 1
            $msg = \sprintf('%s::%s', \get_class($ro), $cacheable->expiryAt);
172 1
            throw new ExpireAtKeyNotExists($msg);
173
        }
174 1
        $expiryAt = $ro->body[$cacheable->expiryAt];
175
176 1
        return \strtotime($expiryAt) - \time();
177
    }
178
179 23
    private function setMaxAge(ResourceObject $ro, int $age)
180
    {
181 23
        $setMaxAge = \sprintf('max-age=%d', $age);
182 23
        if (isset($ro->headers['Cache-Control'])) {
183 6
            $ro->headers['Cache-Control'] .= ', ' . $setMaxAge;
184
185 6
            return;
186
        }
187 20
        $ro->headers['Cache-Control'] = $setMaxAge;
188 20
    }
189
}
190