Completed
Push — 1.x ( 7ee14a...9a27b9 )
by Akihito
145:10 queued 120:09
created

QueryRepository::evaluateBody()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4.5923

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 4
cts 6
cp 0.6667
rs 9.7998
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 4.5923

1 Method

Rating   Name   Duplication   Size   Complexity  
A QueryRepository::getExpiryAtSec() 0 13 2
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\ResourceObject;
12
use Doctrine\Common\Annotations\Reader;
13
use ReflectionClass;
14
use ReflectionException;
15
16
use function assert;
17
use function get_class;
18
use function is_array;
19
use function is_string;
20
use function sprintf;
21
use function strpos;
22
use function strtotime;
23
use function time;
24
25
final class QueryRepository implements QueryRepositoryInterface
26
{
27
    /** @var ResourceStorageInterface */
28
    private $storage;
29
30
    /** @var Reader */
31
    private $reader;
32
33
    /** @var Expiry */
34
    private $expiry;
35
36
    /** @var EtagSetterInterface */
37 29
    private $setEtag;
38
39
    public function __construct(
40
        EtagSetterInterface $setEtag,
41
        ResourceStorageInterface $storage,
42
        Reader $reader,
43 29
        Expiry $expiry
44 29
    ) {
45 29
        $this->setEtag = $setEtag;
46 29
        $this->reader = $reader;
47 29
        $this->storage = $storage;
48
        $this->expiry = $expiry;
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     *
54 27
     * @throws ReflectionException
55
     */
56 27
    public function put(ResourceObject $ro)
57 27
    {
58 27
        $ro->toString();
59 27
        $httpCache = $this->getHttpCacheAnnotation($ro);
60 27
        $cacheable = $this->getCacheableAnnotation($ro);
61 26
        ($this->setEtag)($ro, null, $httpCache);
62 26
        $lifeTime = $this->getExpiryTime($ro, $cacheable);
63
        if (isset($ro->headers['ETag'])) {
64 26
            $this->storage->updateEtag($ro, $lifeTime);
65 26
        }
66 2
67
        $this->setMaxAge($ro, $lifeTime);
68
        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...
69 24
            return $this->saveViewCache($ro, $lifeTime);
70
        }
71
72
        return $this->storage->saveValue($ro, $lifeTime);
73
    }
74
75 25
    /**
76
     * {@inheritdoc}
77 25
     */
78 25
    public function get(AbstractUri $uri)
79 23
    {
80
        $data = $this->storage->get($uri);
81 15
82 15
        if ($data === false) {
83
            return false;
84 15
        }
85
86
        $age = time() - strtotime($data[2]['Last-Modified']);
87
        $data[2]['Age'] = $age;
88
89
        return $data;
90 12
    }
91
92 12
    /**
93
     * {@inheritdoc}
94 12
     */
95
    public function purge(AbstractUri $uri)
96
    {
97
        $this->storage->deleteEtag($uri);
98
99
        return $this->storage->delete($uri);
100 27
    }
101
102 27
    /**
103 27
     * @throws ReflectionException
104 27
     */
105
    private function getHttpCacheAnnotation(ResourceObject $ro): ?HttpCache
106
    {
107
        return $this->reader->getClassAnnotation(new ReflectionClass($ro), HttpCache::class);
108
    }
109
110
    /**
111
     * @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...
112
     *
113
     * @throws ReflectionException
114
     */
115 27
    private function getCacheableAnnotation(ResourceObject $ro): ?Cacheable
116
    {
117 27
        return $this->reader->getClassAnnotation(new ReflectionClass($ro), Cacheable::class);
118 27
    }
119 27
120
    private function getExpiryTime(ResourceObject $ro, ?Cacheable $cacheable = null): int
121
    {
122
        if ($cacheable === null) {
123
            return 0;
124
        }
125
126
        if ($cacheable->expiryAt) {
127
            return $this->getExpiryAtSec($ro, $cacheable);
128
        }
129
130
        return $cacheable->expirySecond ? $cacheable->expirySecond : (int) $this->expiry[$cacheable->expiry];
131
    }
132
133
    private function getExpiryAtSec(ResourceObject $ro, Cacheable $cacheable): int
134
    {
135
        if (! isset($ro->body[$cacheable->expiryAt])) {
136
            $msg = sprintf('%s::%s', get_class($ro), $cacheable->expiryAt);
137
138
            throw new ExpireAtKeyNotExists($msg);
139 28
        }
140
141 28
        assert(is_array($ro->body));
142 4
        $expiryAt = (string) $ro->body[$cacheable->expiryAt];
143
144
        return strtotime($expiryAt) - time();
145 24
    }
146 2
147
    /**
148
     * @return void
149 22
     */
150
    private function setMaxAge(ResourceObject $ro, int $age)
151
    {
152 2
        if ($age === 0) {
153
            return;
154 2
        }
155 1
156
        $setMaxAge = sprintf('max-age=%d', $age);
157 1
        $noCacheControleHeader = ! isset($ro->headers['Cache-Control']);
158
        /** @var array<string, string> $headers */
159 1
        $headers = $ro->headers;
160
        if ($noCacheControleHeader) {
161 1
            $ro->headers['Cache-Control'] = $setMaxAge;
162
163
            return;
164 26
        }
165
166 26
        $isMaxAgeAlreadyDefined = strpos($headers['Cache-Control'], 'max-age') !== false;
167 22
        if ($isMaxAgeAlreadyDefined) {
168
            return;
169 4
        }
170 4
171 4
        if (is_string($ro->headers['Cache-Control'])) {
172 1
            $ro->headers['Cache-Control'] .= ', ' . $setMaxAge;
173
        }
174 1
    }
175
176 3
    private function saveViewCache(ResourceObject $ro, int $lifeTime): bool
177 3
    {
178 1
        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...
179
            $ro->view = $ro->toString();
180 2
        }
181 2
182
        return $this->storage->saveView($ro, $lifeTime);
183 2
    }
184
}
185