Completed
Pull Request — 1.x (#51)
by Akihito
02:03
created

QueryRepository::setMaxAge()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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