QueryRepository::getExpiryAtSec()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 2
nop 2
dl 0
loc 12
rs 10
c 0
b 0
f 0
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 Override;
13
use ReflectionClass;
14
15
use function is_array;
16
use function sprintf;
17
use function strtotime;
18
use function time;
19
20
final class QueryRepository implements QueryRepositoryInterface
21
{
22
    public function __construct(
23
        private readonly RepositoryLoggerInterface $logger,
24
        private readonly HeaderSetter $headerSetter,
25
        private readonly ResourceStorageInterface $storage,
26
        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...
27
    ) {
28
    }
29
30
    /**
31
     * {@inheritDoc}
32
     */
33
    #[Override]
34
    public function put(ResourceObject $ro)
35
    {
36
        $this->logger->log('put-query-repository uri:%s', $ro->uri);
37
        $this->storage->deleteEtag($ro->uri);
38
        $ro->toString();
39
        $cacheable = $this->getCacheableAnnotation($ro);
40
        $httpCache = $this->getHttpCacheAnnotation($ro);
41
        $ttl = $this->getExpiryTime($ro, $cacheable);
42
        ($this->headerSetter)($ro, $ttl, $httpCache);
43
        if (isset($ro->headers[Header::ETAG])) {
44
            $etag = $ro->headers[Header::ETAG];
45
            $surrogateKeys = $ro->headers[Header::SURROGATE_KEY] ?? '';
46
            $this->storage->saveEtag($ro->uri, $etag, $surrogateKeys, $ttl);
47
        }
48
49
        if ($cacheable instanceof Cacheable && $cacheable->type === 'view') {
50
            return $this->storage->saveView($ro, $ttl);
51
        }
52
53
        return $this->storage->saveValue($ro, $ttl);
54
    }
55
56
    /**
57
     * {@inheritDoc}
58
     */
59
    #[Override]
60
    public function get(AbstractUri $uri): ResourceState|null
61
    {
62
        $state = $this->storage->get($uri);
63
64
        if (! $state instanceof ResourceState) {
65
            return null;
66
        }
67
68
        $state->headers[Header::AGE] = (string) (time() - (int) strtotime($state->headers[Header::LAST_MODIFIED]));
69
70
        return $state;
71
    }
72
73
    /**
74
     * {@inheritDoc}
75
     */
76
    #[Override]
77
    public function purge(AbstractUri $uri)
78
    {
79
        $this->logger->log('purge-query-repository uri:%s', $uri);
80
81
        return $this->storage->deleteEtag($uri);
82
    }
83
84
    private function getHttpCacheAnnotation(ResourceObject $ro): HttpCache|null
85
    {
86
        $attributes = (new ReflectionClass($ro))->getAttributes(HttpCache::class);
87
88
        return isset($attributes[0]) ? $attributes[0]->newInstance() : null;
89
    }
90
91
    private function getCacheableAnnotation(ResourceObject $ro): Cacheable|null
92
    {
93
        $attributes = (new ReflectionClass($ro))->getAttributes(Cacheable::class);
94
95
        return isset($attributes[0]) ? $attributes[0]->newInstance() : null;
96
    }
97
98
    private function getExpiryTime(ResourceObject $ro, Cacheable|null $cacheable = null): int
99
    {
100
        if ($cacheable === null) {
101
            return 0;
102
        }
103
104
        if ($cacheable->expiryAt !== '') {
105
            return $this->getExpiryAtSec($ro, $cacheable);
106
        }
107
108
        return $cacheable->expirySecond ?: $this->expiry->getTime($cacheable->expiry);
109
    }
110
111
    private function getExpiryAtSec(ResourceObject $ro, Cacheable $cacheable): int
112
    {
113
        if (! is_array($ro->body) || ! isset($ro->body[$cacheable->expiryAt])) {
114
            $msg = sprintf('%s::%s', $ro::class, $cacheable->expiryAt);
115
116
            throw new ExpireAtKeyNotExists($msg);
117
        }
118
119
        /** @var string $expiryAt */
120
        $expiryAt = $ro->body[$cacheable->expiryAt];
121
122
        return (int) strtotime($expiryAt) - time();
123
    }
124
}
125