ResourceStorage::saveDonutView()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 9
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\QueryRepository;
6
7
use BEAR\RepositoryModule\Annotation\EtagPool;
8
use BEAR\RepositoryModule\Annotation\ResourceObjectPool;
9
use BEAR\Resource\AbstractUri;
10
use BEAR\Resource\RequestInterface;
11
use BEAR\Resource\ResourceObject;
12
use Override;
13
use Ray\Di\Di\Set;
14
use Ray\Di\ProviderInterface;
15
use Symfony\Component\Cache\Adapter\TagAwareAdapterInterface;
16
17
use function array_merge;
18
use function array_unique;
19
use function array_values;
20
use function assert;
21
use function explode;
22
use function implode;
23
use function is_array;
24
use function is_string;
25
use function sprintf;
26
use function strtoupper;
27
28
/**
29
 * @psalm-type Props = array{
30
 *     logger: RepositoryLoggerInterface,
31
 *     purger:PurgerInterface,
32
 *     uriTag: UriTag,
33
 *     saver: ResourceStorageSaver,
34
 *     roProvider:ProviderInterface<TagAwareAdapterInterface>,
35
 *     etagProvider: ProviderInterface<TagAwareAdapterInterface>
36
 * }
37
 */
38
final class ResourceStorage implements ResourceStorageInterface
39
{
40
    /**
41
     * Resource object cache prefix
42
     */
43
    private const KEY_RO = 'ro-';
44
45
    /**
46
     * Resource static cache prifix
47
     */
48
    private const KEY_DONUT = 'donut-';
49
50
    /** @var ProviderInterface<TagAwareAdapterInterface> */
51
    private ProviderInterface $roPoolProvider;
52
53
    /** @var ProviderInterface<TagAwareAdapterInterface> */
54
    private ProviderInterface $etagPoolProvider;
55
    private TagAwareAdapterInterface $roPool;
56
    private TagAwareAdapterInterface $etagPool;
57
58
    /**
59
     * @param ProviderInterface<TagAwareAdapterInterface> $roPoolProvider
60
     * @param ProviderInterface<TagAwareAdapterInterface> $etagPoolProvider
61
     */
62
    public function __construct(
63
        private RepositoryLoggerInterface $logger,
64
        private PurgerInterface $purger,
65
        private UriTagInterface $uriTag,
66
        private ResourceStorageSaver $saver,
67
        #[Set(TagAwareAdapterInterface::class, ResourceObjectPool::class)]
68
        ProviderInterface $roPoolProvider,
69
        #[Set(TagAwareAdapterInterface::class, EtagPool::class)]
70
        ProviderInterface $etagPoolProvider,
71
    ) {
72
        $this->initializePools($roPoolProvider, $etagPoolProvider);
73
    }
74
75
    /**
76
     * @param ProviderInterface<TagAwareAdapterInterface> $roPoolProvider
77
     * @param ProviderInterface<TagAwareAdapterInterface> $etagPoolProvider
78
     */
79
    private function initializePools(ProviderInterface $roPoolProvider, ProviderInterface $etagPoolProvider): void
80
    {
81
        $this->roPoolProvider = $roPoolProvider;
82
        $this->etagPoolProvider = $etagPoolProvider;
83
        $this->roPool = $roPoolProvider->get();
84
        $etagPool = $this->etagPoolProvider->get();
85
        $this->etagPool = $etagPool instanceof TagAwareAdapterInterface ? $etagPool : $this->roPool; // @phpstan-ignore-line
86
    }
87
88
    /**
89
     * {@inheritDoc}
90
     */
91
    #[Override]
92
    public function get(AbstractUri $uri): ResourceState|null
93
    {
94
        $item = $this->roPool->getItem($this->getUriKey($uri, self::KEY_RO));
95
        $state = $item->get();
96
        assert($state instanceof ResourceState || $state === null);
97
98
        return $state;
99
    }
100
101
    #[Override]
102
    public function getDonut(AbstractUri $uri): ResourceDonut|null
103
    {
104
        $key = $this->getUriKey($uri, self::KEY_DONUT);
105
        $item = $this->roPool->getItem($key);
106
        $donut = $item->get();
107
        assert($donut instanceof ResourceDonut || $donut === null);
108
109
        return $donut;
110
    }
111
112
    /**
113
     * {@inheritDoc}
114
     */
115
    #[Override]
116
    public function hasEtag(string $etag): bool
117
    {
118
        return $this->etagPool->hasItem($etag);
119
    }
120
121
    /**
122
     * {@inheritDoc}
123
     */
124
    #[Override]
125
    public function deleteEtag(AbstractUri $uri)
126
    {
127
        $uriTag = ($this->uriTag)($uri);
128
129
        return $this->invalidateTags([$uriTag]);
130
    }
131
132
    /**
133
     * {@inheritDoc}
134
     */
135
    #[Override]
136
    public function invalidateTags(array $tags): bool
137
    {
138
        $this->logger->log('invalidate-etag', ['tags' => $tags]);
139
        $valid1 = $this->roPool->invalidateTags($tags);
140
        $valid2 = $this->etagPool->invalidateTags($tags);
141
        ($this->purger)(implode(' ', $tags));
142
143
        return $valid1 && $valid2;
144
    }
145
146
    /**
147
     * {@inheritDoc}
148
     *
149
     * @return bool
150
     */
151
    #[Override]
152
    public function saveValue(ResourceObject $ro, int $ttl)
153
    {
154
        /** @psalm-suppress MixedAssignment $body */
155
        $body = $this->evaluateBody($ro->body);
156
        $value = ResourceState::create($ro, $body, null);
157
        $key = $this->getUriKey($ro->uri, self::KEY_RO);
158
        $tags = $this->getTags($ro);
159
        $this->logger->log('save-value', ['uri' => (string) $ro->uri, 'tags' => $tags, 'ttl' => $ttl]);
160
161
        return $this->saver->__invoke($key, $value, $this->roPool, $tags, $ttl);
162
    }
163
164
    /**
165
     * {@inheritDoc}
166
     *
167
     * @return bool
168
     */
169
    #[Override]
170
    public function saveView(ResourceObject $ro, int $ttl)
171
    {
172
        $this->logger->log('save-view', ['uri' => (string) $ro->uri, 'ttl' => $ttl]);
173
        /** @psalm-suppress MixedAssignment $body */
174
        $body = $this->evaluateBody($ro->body);
175
        $value = ResourceState::create($ro, $body, $ro->view);
176
        $key = $this->getUriKey($ro->uri, self::KEY_RO);
177
        $tags = $this->getTags($ro);
178
179
        return $this->saver->__invoke($key, $value, $this->roPool, $tags, $ttl);
180
    }
181
182
    /**
183
     * {@inheritDoc}
184
     */
185
    #[Override]
186
    public function saveDonut(AbstractUri $uri, ResourceDonut $donut, int|null $sMaxAge, array $headerKeys): void
187
    {
188
        $key = $this->getUriKey($uri, self::KEY_DONUT);
189
        $this->logger->log('save-donut', ['uri' => (string) $uri, 'sMaxAge' => $sMaxAge]);
190
        $result = $this->saver->__invoke($key, $donut, $this->roPool, $headerKeys, $sMaxAge);
191
        assert($result, 'Donut save failed.');
192
    }
193
194
    #[Override]
195
    public function saveDonutView(ResourceObject $ro, int|null $ttl): bool
196
    {
197
        $resourceState = ResourceState::create($ro, [], $ro->view);
198
        $key = $this->getUriKey($ro->uri, self::KEY_RO);
199
        $tags = $this->getTags($ro);
200
        $this->logger->log('save-donut-view', ['uri' => (string) $ro->uri, 'surrogateKeys' => $tags, 'sMaxAge' => $ttl]);
201
202
        return $this->saver->__invoke($key, $resourceState, $this->roPool, $tags, $ttl);
203
    }
204
205
    /** @return list<string> */
0 ignored issues
show
Bug introduced by
The type BEAR\QueryRepository\list 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...
206
    private function getTags(ResourceObject $ro): array
207
    {
208
        $etag = $ro->headers['ETag'];
209
        $tags = [$etag, ($this->uriTag)($ro->uri)];
210
        if (isset($ro->headers[Header::SURROGATE_KEY])) {
211
            $tags = array_merge($tags, explode(' ', $ro->headers[Header::SURROGATE_KEY]));
212
        }
213
214
        /** @var list<string> $uniqueTags */
215
        $uniqueTags = array_values(array_unique($tags));
216
217
        return $uniqueTags;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $uniqueTags returns the type BEAR\QueryRepository\list which is incompatible with the type-hinted return array.
Loading history...
218
    }
219
220
    private function evaluateBody(mixed $body): mixed
221
    {
222
        if (! is_array($body)) {
223
            return $body;
224
        }
225
226
        /** @psalm-suppress MixedAssignment $item */
227
        foreach ($body as &$item) {
228
            if ($item instanceof RequestInterface) {
229
                $item = ($item)();
230
            }
231
232
            if ($item instanceof ResourceObject) {
233
                $item->body = $this->evaluateBody($item->body);
234
            }
235
        }
236
237
        return $body;
238
    }
239
240
    private function getUriKey(AbstractUri $uri, string $type): string
241
    {
242
        return $type . ($this->uriTag)($uri) . (isset($_SERVER['X_VARY']) ? $this->getVary() : '');
243
    }
244
245
    private function getVary(): string
246
    {
247
        $xvary = $_SERVER['X_VARY'];
248
        /** @psalm-suppress RedundantCast */
249
        $varys = explode(',', (string) $xvary); // @phpstan-ignore-line
250
        $varyString = '';
251
        foreach ($varys as $vary) {
252
            $phpVaryKey = sprintf('X_%s', strtoupper($vary));
253
            if (isset($_SERVER[$phpVaryKey]) && is_string($_SERVER[$phpVaryKey])) {
254
                $varyString .= $_SERVER[$phpVaryKey];
255
            }
256
        }
257
258
        return $varyString;
259
    }
260
261
    #[Override]
262
    public function saveEtag(AbstractUri $uri, string $etag, string $surrogateKeys, int|null $ttl): void
263
    {
264
        $tags = $surrogateKeys !== '' ? explode(' ', $surrogateKeys) : [];
265
        $tags[] = (new UriTag())($uri);
266
        /** @var list<string> $uniqueTags */
267
        $uniqueTags = array_values(array_unique($tags));
268
        $this->logger->log('save-etag', ['uri' => (string) $uri, 'etag' => $etag, 'surrogateKeys' => $uniqueTags]);
269
        // Sanitize etag to remove reserved characters
270
        $this->saver->__invoke($etag, 'etag', $this->etagPool, $uniqueTags, $ttl);
0 ignored issues
show
Bug introduced by
$uniqueTags of type BEAR\QueryRepository\list is incompatible with the type array expected by parameter $tags of BEAR\QueryRepository\Res...torageSaver::__invoke(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

270
        $this->saver->__invoke($etag, 'etag', $this->etagPool, /** @scrutinizer ignore-type */ $uniqueTags, $ttl);
Loading history...
271
    }
272
273
    public function __serialize(): array
274
    {
275
        return [
276
            'logger' => $this->logger,
277
            'purger' => $this->purger,
278
            'uriTag' => $this->uriTag,
279
            'saver' => $this->saver,
280
            'roProvider' => $this->roPoolProvider,
281
            'etagProvider' => $this->etagPoolProvider,
282
        ];
283
    }
284
285
    /**
286
     * @param Props $data
0 ignored issues
show
Bug introduced by
The type BEAR\QueryRepository\Props 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...
287
     *
288
     * @return void
289
     */
290
    public function __unserialize(array $data): void
291
    {
292
        $this->logger = $data['logger'];
293
        $this->purger = $data['purger'];
294
        $this->uriTag = $data['uriTag'];
295
        $this->saver = $data['saver'];
296
        $this->initializePools($data['roProvider'], $data['etagProvider']);
297
    }
298
}
299