Completed
Pull Request — 1.x (#51)
by Akihito
01:31
created

QueryRepository::getExpiryAtSec()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 11
c 0
b 0
f 0
ccs 0
cts 0
cp 0
rs 9.9
cc 2
nc 2
nop 2
crap 6
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\Storage;
12
use BEAR\Resource\AbstractUri;
13
use BEAR\Resource\RequestInterface;
14
use BEAR\Resource\ResourceObject;
15
use Doctrine\Common\Annotations\Reader;
16
use Doctrine\Common\Cache\Cache;
17
18
class QueryRepository implements QueryRepositoryInterface
19
{
20
    const ETAG_BY_URI = 'etag-by-uri';
21
22
    /**
23
     * @var Cache
24
     */
25
    private $kvs;
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
    public function __construct(
46
        EtagSetterInterface $setEtag,
47
        Cache $kvs,
48
        Reader $reader,
49
        Expiry $expiry
50
    ) {
51 16
        $this->setEtag = $setEtag;
52
        $this->reader = $reader;
53
        $this->kvs = $kvs;
54
        $this->expiry = $expiry;
55
    }
56
57 16
    /**
58 16
     * {@inheritdoc}
59 16
     */
60 16
    public function put(ResourceObject $ro)
61 16
    {
62
        $ro->toString();
63
        ($this->setEtag)($ro);
64
        if (isset($ro->headers['ETag'])) {
65
            $this->updateEtagDatabase($ro);
66 14
        }
67
        /* @var $cacheable Cacheable */
68 14
        $cacheable = $this->getCacheable($ro);
69 14
        $body = $this->evaluateBody($ro->body);
70 14
        $lifeTime = $this->getExpiryTime($ro, $cacheable);
71
        $this->setMaxAge($ro, $lifeTime);
72
        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...
73 14
            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...
74 14
                // render
75 14
                $ro->view = $ro->toString();
76 1
            }
77
78 1
            return $this->kvs->save((string) $ro->uri, [$ro->uri, $ro->code, $ro->headers, $body, $ro->view], $lifeTime);
79
        }
80
        // "value" cache type
81 1
        return $this->kvs->save((string) $ro->uri, [$ro->uri, $ro->code, $ro->headers, $body, null], $lifeTime);
82
    }
83
84 13
    /**
85
     * {@inheritdoc}
86
     */
87
    public function get(AbstractUri $uri)
88
    {
89
        $data = $this->kvs->fetch((string) $uri);
90 14
        if ($data === false) {
91
            return false;
92 14
        }
93 14
94 13
        return $data;
95
    }
96
97 10
    /**
98
     * {@inheritdoc}
99
     */
100
    public function purge(AbstractUri $uri)
101
    {
102
        $this->deleteEtagDatabase($uri);
103 9
104
        return $this->kvs->delete((string) $uri);
105 9
    }
106
107 9
    /**
108
     * Delete etag in etag repository
109
     *
110
     * @param AbstractUri $uri
111
     */
112
    public function deleteEtagDatabase(AbstractUri $uri)
113
    {
114
        $etagId = self::ETAG_BY_URI . (string) $uri; // invalidate etag
115 9
        $oldEtagKey = $this->kvs->fetch($etagId);
116
117 9
        $this->kvs->delete($oldEtagKey);
118 9
    }
119
120 9
    private function evaluateBody($body)
121 9
    {
122
        if (! \is_array($body)) {
123
            return $body;
124
        }
125
        foreach ($body as &$item) {
126 14
            if ($item instanceof RequestInterface) {
127
                $item = ($item)();
128 14
            }
129 12
        }
130
131 12
        return $body;
132
    }
133
134 2
    /**
135
     * @return Cacheable|null
136
     */
137
    private function getCacheable(ResourceObject $ro)
138
    {
139
        /** @var Cacheable|null $cache */
140
        $cache = $this->reader->getClassAnnotation(new \ReflectionClass($ro), Cacheable::class);
141
142 14
        return $cache;
143
    }
144 14
145 14
    /**
146 14
     * Update etag in etag repository
147 14
     *
148 14
     * @param ResourceObject $ro
149 7
     */
150
    private function updateEtagDatabase(ResourceObject $ro)
151 14
    {
152 14
        $etag = $ro->headers['ETag'];
153 14
        $uri = (string) $ro->uri;
154 14
        $etagUri = self::ETAG_BY_URI . $uri;
155
        $oldEtag = $this->kvs->fetch($etagUri);
156
        if ($oldEtag) {
157
            $this->kvs->delete($oldEtag);
158
        }
159
        $etagId = HttpCache::ETAG_KEY . $etag;
160
        $this->kvs->save($etagId, $uri);     // save etag
161 15
        $this->kvs->save($etagUri, $etagId); // save uri  mapping etag
162
    }
163 15
164 1
    private function getExpiryTime(ResourceObject $ro, Cacheable $cacheable = null) : int
165
    {
166
        if ($cacheable === null) {
167 14
            return 0;
168
        }
169
170
        if ($cacheable->expiryAt) {
171
            return $this->getExpiryAtSec($ro, $cacheable);
172
        }
173
174
        return $cacheable->expirySecond ? $cacheable->expirySecond : $this->expiry[$cacheable->expiry];
175
    }
176
177
    private function getExpiryAtSec(ResourceObject $ro, Cacheable $cacheable) : int
178
    {
179
        if (! isset($ro->body[$cacheable->expiryAt])) {
180
            $msg = \sprintf('%s::%s', \get_class($ro), $cacheable->expiryAt);
181
            throw new ExpireAtKeyNotExists($msg);
182
        }
183
        $expiryAt = $ro->body[$cacheable->expiryAt];
184
        $sec = \strtotime($expiryAt) - \time();
185
186
        return $sec;
187
    }
188
189
    private function setMaxAge(ResourceObject $ro, int $age)
190
    {
191
        $setMaxAge = \sprintf('max-age=%d', $age);
192
        if (isset($ro->headers['Cache-Control'])) {
193
            $ro->headers['Cache-Control'] .= ', ' . $setMaxAge;
194
195
            return;
196
        }
197
        $ro->headers['Cache-Control'] = $setMaxAge;
198
    }
199
}
200