Completed
Push — fix-body ( 1eb8ea )
by Akihito
02:19
created

QueryRepository::evaluateBody()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 4
nc 4
nop 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\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
        $this->reader = $reader;
52
        $this->kvs = $kvs;
53
        $this->expiry = $expiry;
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function put(ResourceObject $ro)
60
    {
61
        $ro->toString();
62
        ($this->setEtag)($ro);
63
        if (isset($ro->headers['ETag'])) {
64
            $this->updateEtagDatabase($ro);
65
        }
66
        /* @var $cacheable Cacheable */
67
        $cacheable = $this->getCacheable($ro);
68
        $lifeTime = $this->getExpiryTime($cacheable);
69
        $body = $this->evaluateBody($ro->body);
70
        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...
71
            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...
72
                // render
73
                $ro->view = $ro->toString();
74
            }
75
76
            return $this->kvs->save((string) $ro->uri, [$ro->uri, $ro->code, $ro->headers, $body, $ro->view], $lifeTime);
77
        }
78
        // "value" cache type
79
        return $this->kvs->save((string) $ro->uri, [$ro->uri, $ro->code, $ro->headers, $body, null], $lifeTime);
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85
    public function get(AbstractUri $uri)
86
    {
87
        $data = $this->kvs->fetch((string) $uri);
88
        if ($data === false) {
89
            return false;
90
        }
91
92
        return $data;
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    public function purge(AbstractUri $uri)
99
    {
100
        $this->deleteEtagDatabase($uri);
101
102
        return $this->kvs->delete((string) $uri);
103
    }
104
105
    /**
106
     * Delete etag in etag repository
107
     *
108
     * @param AbstractUri $uri
109
     */
110
    public function deleteEtagDatabase(AbstractUri $uri)
111
    {
112
        $etagId = self::ETAG_BY_URI . (string) $uri; // invalidate etag
113
        $oldEtagKey = $this->kvs->fetch($etagId);
114
115
        $this->kvs->delete($oldEtagKey);
116
    }
117
118
    private function evaluateBody($body)
119
    {
120
        if (! \is_array($body)) {
121
            return $body;
122
        }
123
        foreach ($body as &$item) {
124
            if ($item instanceof RequestInterface) {
125
                $item = ($item)();
126
            }
127
        }
128
129
        return $body;
130
    }
131
132
    /**
133
     * @return Cacheable|null
134
     */
135
    private function getCacheable(ResourceObject $ro)
136
    {
137
        /** @var Cacheable|null $cache */
138
        $cache = $this->reader->getClassAnnotation(new \ReflectionClass($ro), Cacheable::class);
139
140
        return $cache;
141
    }
142
143
    /**
144
     * Update etag in etag repository
145
     *
146
     * @param ResourceObject $ro
147
     */
148
    private function updateEtagDatabase(ResourceObject $ro)
149
    {
150
        $etag = $ro->headers['ETag'];
151
        $uri = (string) $ro->uri;
152
        $etagUri = self::ETAG_BY_URI . $uri;
153
        $oldEtag = $this->kvs->fetch($etagUri);
154
        if ($oldEtag) {
155
            $this->kvs->delete($oldEtag);
156
        }
157
        $etagId = HttpCache::ETAG_KEY . $etag;
158
        $this->kvs->save($etagId, $uri);     // save etag
159
        $this->kvs->save($etagUri, $etagId); // save uri  mapping etag
160
    }
161
162
    /**
163
     * @param Cacheable $cacheable
164
     *
165
     * @return int
166
     */
167
    private function getExpiryTime(Cacheable $cacheable = null)
168
    {
169
        if ($cacheable === null) {
170
            return 0;
171
        }
172
173
        return $cacheable->expirySecond ? $cacheable->expirySecond : $this->expiry[$cacheable->expiry];
174
    }
175
}
176