Completed
Push — 1.x ( 6438f2...004925 )
by Akihito
12s
created

QueryRepository::evaluateBody()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 0
cts 7
cp 0
rs 9.8333
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 20
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\QueryRepository;
6
7
use BEAR\QueryRepository\Exception\ExpireAtKeyNotExists;
8
use BEAR\RepositoryModule\Annotation\Cacheable;
9
use BEAR\RepositoryModule\Annotation\HttpCache;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, BEAR\QueryRepository\HttpCache.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
10
use BEAR\Resource\AbstractUri;
11
use BEAR\Resource\RequestInterface;
12
use BEAR\Resource\ResourceObject;
13
use Doctrine\Common\Annotations\Reader;
14
15
final class QueryRepository implements QueryRepositoryInterface
16
{
17
    const ETAG_BY_URI = 'etag-by-uri';
18
19
    /**
20
     * @var ResourceStorageInterface
21
     */
22
    private $storage;
23
24
    /**
25
     * @var Reader
26
     */
27
    private $reader;
28
29
    /**
30
     * @var Expiry
31
     */
32
    private $expiry;
33
34
    /**
35
     * @var EtagSetterInterface
36
     */
37
    private $setEtag;
38
39 28
    public function __construct(
40
        EtagSetterInterface $setEtag,
41
        ResourceStorageInterface $storage,
42
        Reader $reader,
43
        Expiry $expiry
44
    ) {
45 28
        $this->setEtag = $setEtag;
46 28
        $this->reader = $reader;
47 28
        $this->storage = $storage;
48 28
        $this->expiry = $expiry;
49 28
    }
50
51
    /**
52
     * {@inheritdoc}
53
     *
54
     * @throws \ReflectionException
55
     */
56 26
    public function put(ResourceObject $ro)
57
    {
58 26
        $ro->toString();
59 26
        $httpCache = $this->getHttpCacheAnnotation($ro);
60 26
        $cacheable = $this->getCacheableAnnotation($ro);
61 26
        ($this->setEtag)($ro, null, $httpCache);
62 26
        $lifeTime = $this->getExpiryTime($ro, $cacheable);
63 25
        if (isset($ro->headers['ETag'])) {
64 25
            $this->storage->updateEtag($ro, $lifeTime);
65
        }
66 25
        $this->setMaxAge($ro, $lifeTime);
67 25
        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...
68 2
            return $this->saveViewCache($ro, $lifeTime);
69
        }
70
71 23
        return $this->storage->saveValue($ro, $lifeTime);
72
    }
73
74
    /**
75
     * {@inheritdoc}
76
     */
77 24
    public function get(AbstractUri $uri)
78
    {
79 24
        $data = $this->storage->get($uri);
80 24
        if ($data === false) {
81 22
            return false;
82
        }
83 14
        $age = \time() - \strtotime($data[2]['Last-Modified']);
84 14
        $data[2]['Age'] = $age;
85
86 14
        return $data;
87
    }
88
89
    /**
90
     * {@inheritdoc}
91
     */
92 12
    public function purge(AbstractUri $uri)
93
    {
94 12
        $this->storage->deleteEtag($uri);
95
96 12
        return $this->storage->delete($uri);
97
    }
98
99
    /**
100
     * @throws \ReflectionException
101
     */
102 26
    private function getHttpCacheAnnotation(ResourceObject $ro)
103
    {
104 26
        $annotation = $this->reader->getClassAnnotation(new \ReflectionClass($ro), HttpCache::class);
105 26
        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...
106 26
            return $annotation;
107
        }
108
109
        throw new \LogicException();
110
    }
111
112
    /**
113
     * @throws \ReflectionException
114
     *
115
     * @return ?Cacheable
0 ignored issues
show
Documentation introduced by
The doc-type ?Cacheable could not be parsed: Unknown type name "?Cacheable" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
116
     */
117 26
    private function getCacheableAnnotation(ResourceObject $ro)
118
    {
119 26
        $annotation = $this->reader->getClassAnnotation(new \ReflectionClass($ro), Cacheable::class);
120 26
        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...
121 26
            return $annotation;
122
        }
123
124
        throw new \LogicException();
125
    }
126
127
    private function evaluateBody($body)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
128
    {
129
        if (! \is_array($body)) {
130
            return $body;
131
        }
132
        foreach ($body as &$item) {
133
            if ($item instanceof RequestInterface) {
134
                $item = ($item)();
135
            }
136
        }
137
138
        return $body;
139
    }
140
141 27
    private function getExpiryTime(ResourceObject $ro, Cacheable $cacheable = null) : int
142
    {
143 27
        if ($cacheable === null) {
144 4
            return 0;
145
        }
146
147 23
        if ($cacheable->expiryAt) {
148 2
            return $this->getExpiryAtSec($ro, $cacheable);
149
        }
150
151 21
        return $cacheable->expirySecond ? $cacheable->expirySecond : $this->expiry[$cacheable->expiry];
152
    }
153
154 2
    private function getExpiryAtSec(ResourceObject $ro, Cacheable $cacheable) : int
155
    {
156 2
        if (! isset($ro->body[$cacheable->expiryAt])) {
157 1
            $msg = \sprintf('%s::%s', \get_class($ro), $cacheable->expiryAt);
158
159 1
            throw new ExpireAtKeyNotExists($msg);
160
        }
161 1
        $expiryAt = $ro->body[$cacheable->expiryAt];
162
163 1
        return \strtotime($expiryAt) - \time();
164
    }
165
166 25
    private function setMaxAge(ResourceObject $ro, int $age)
167
    {
168 25
        $setMaxAge = \sprintf('max-age=%d', $age);
169 25
        $noCacheControleHeader = ! isset($ro->headers['Cache-Control']);
170 25
        if ($noCacheControleHeader) {
171 20
            $ro->headers['Cache-Control'] = $setMaxAge;
172
173 20
            return;
174
        }
175 8
        $isMaxAgeAlreadyDefined = strpos($ro->headers['Cache-Control'], 'max-age') !== false;
176 8
        if ($isMaxAgeAlreadyDefined) {
177 4
            return;
178
        }
179 4
        $ro->headers['Cache-Control'] .= ', ' . $setMaxAge;
180 4
    }
181
182 2
    private function saveViewCache(ResourceObject $ro, int $lifeTime)
183
    {
184 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...
185
            $ro->view = $ro->toString();
186
        }
187
188 2
        return $this->storage->saveView($ro, $lifeTime);
189
    }
190
}
191