QueryRepository::getExpiryTime()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 5
nc 3
nop 2
dl 0
loc 11
rs 10
c 1
b 0
f 0
ccs 4
cts 4
cp 1
crap 4
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. Consider defining an alias.

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 Override;
14
use ReflectionClass;
15
16
use function is_array;
17
use function sprintf;
18
use function strtotime;
19
use function time;
20
21
final class QueryRepository implements QueryRepositoryInterface
22
{
23
    public function __construct(
24
        private readonly RepositoryLoggerInterface $logger,
25
        private readonly HeaderSetter $headerSetter,
26
        private readonly ResourceStorageInterface $storage,
27
        private readonly Reader $reader,
28
        private readonly Expiry $expiry,
0 ignored issues
show
Bug introduced by
The type BEAR\QueryRepository\Expiry was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
29
    ) {
30
    }
31
32
    /**
33
     * {@inheritDoc}
34
     */
35
    #[Override]
36
    public function put(ResourceObject $ro)
37 29
    {
38
        $this->logger->log('put-query-repository uri:%s', $ro->uri);
39
        $this->storage->deleteEtag($ro->uri);
40
        $ro->toString();
41
        $cacheable = $this->getCacheableAnnotation($ro);
42
        $httpCache = $this->getHttpCacheAnnotation($ro);
43 29
        $ttl = $this->getExpiryTime($ro, $cacheable);
44 29
        ($this->headerSetter)($ro, $ttl, $httpCache);
45 29
        if (isset($ro->headers[Header::ETAG])) {
46 29
            $etag = $ro->headers[Header::ETAG];
47 29
            $surrogateKeys = $ro->headers[Header::SURROGATE_KEY] ?? '';
48
            $this->storage->saveEtag($ro->uri, $etag, $surrogateKeys, $ttl);
49
        }
50
51
        if ($cacheable instanceof Cacheable && $cacheable->type === 'view') {
52
            return $this->storage->saveView($ro, $ttl);
53
        }
54 27
55
        return $this->storage->saveValue($ro, $ttl);
56 27
    }
57 27
58 27
    /**
59 27
     * {@inheritDoc}
60 27
     */
61 26
    #[Override]
62 26
    public function get(AbstractUri $uri): ResourceState|null
63
    {
64 26
        $state = $this->storage->get($uri);
65 26
66 2
        if (! $state instanceof ResourceState) {
67
            return null;
68
        }
69 24
70
        $state->headers[Header::AGE] = (string) (time() - (int) strtotime($state->headers[Header::LAST_MODIFIED]));
71
72
        return $state;
73
    }
74
75 25
    /**
76
     * {@inheritDoc}
77 25
     */
78 25
    #[Override]
79 23
    public function purge(AbstractUri $uri)
80
    {
81 15
        $this->logger->log('purge-query-repository uri:%s', $uri);
82 15
83
        return $this->storage->deleteEtag($uri);
84 15
    }
85
86
    private function getHttpCacheAnnotation(ResourceObject $ro): HttpCache|null
87
    {
88
        return $this->reader->getClassAnnotation(new ReflectionClass($ro), HttpCache::class);
89
    }
90 12
91
    private function getCacheableAnnotation(ResourceObject $ro): Cacheable|null
92 12
    {
93
        return $this->reader->getClassAnnotation(new ReflectionClass($ro), Cacheable::class);
94 12
    }
95
96
    private function getExpiryTime(ResourceObject $ro, Cacheable|null $cacheable = null): int
97
    {
98
        if ($cacheable === null) {
99
            return 0;
100 27
        }
101
102 27
        if ($cacheable->expiryAt !== '') {
103 27
            return $this->getExpiryAtSec($ro, $cacheable);
104 27
        }
105
106
        return $cacheable->expirySecond ?: $this->expiry->getTime($cacheable->expiry);
107
    }
108
109
    private function getExpiryAtSec(ResourceObject $ro, Cacheable $cacheable): int
110
    {
111
        if (! is_array($ro->body) || ! isset($ro->body[$cacheable->expiryAt])) {
112
            $msg = sprintf('%s::%s', $ro::class, $cacheable->expiryAt);
113
114
            throw new ExpireAtKeyNotExists($msg);
115 27
        }
116
117 27
        /** @var string $expiryAt */
118 27
        $expiryAt = $ro->body[$cacheable->expiryAt];
119 27
120
        return (int) strtotime($expiryAt) - time();
121
    }
122
}
123