Completed
Push — EZP-30968-count-reverse-relati... ( c55217 )
by
unknown
27:08 queued 08:53
created

ContentHandler::countReverseRelations()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
cc 1
nc 1
nop 2
rs 10
1
<?php
2
3
/**
4
 * File containing the ContentHandler implementation.
5
 *
6
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
7
 * @license For full copyright and license information view LICENSE file distributed with this source code.
8
 */
9
namespace eZ\Publish\Core\Persistence\Cache;
10
11
use eZ\Publish\API\Repository\Values\Content\Relation as APIRelation;
12
use eZ\Publish\SPI\Persistence\Content\Handler as ContentHandlerInterface;
13
use eZ\Publish\SPI\Persistence\Content;
14
use eZ\Publish\SPI\Persistence\Content\VersionInfo;
15
use eZ\Publish\SPI\Persistence\Content\ContentInfo;
16
use eZ\Publish\SPI\Persistence\Content\CreateStruct;
17
use eZ\Publish\SPI\Persistence\Content\UpdateStruct;
18
use eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct;
19
use eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct as RelationCreateStruct;
20
21
/**
22
 * @see \eZ\Publish\SPI\Persistence\Content\Handler
23
 */
24
class ContentHandler extends AbstractInMemoryPersistenceHandler implements ContentHandlerInterface
25
{
26
    const ALL_TRANSLATIONS_KEY = '0';
27
28
    /** @var callable */
29
    private $getContentInfoTags;
30
31
    /** @var callable */
32
    private $getContentInfoKeys;
33
34
    /** @var callable */
35
    private $getContentTags;
36
37
    protected function init(): void
38
    {
39
        $this->getContentInfoTags = function (ContentInfo $info, array $tags = []) {
40
            $tags[] = 'content-' . $info->id;
41
42
            if ($info->mainLocationId) {
43
                $locations = $this->persistenceHandler->locationHandler()->loadLocationsByContent($info->id);
44
                foreach ($locations as $location) {
45
                    $tags[] = 'location-' . $location->id;
46
                    foreach (explode('/', trim($location->pathString, '/')) as $pathId) {
47
                        $tags[] = 'location-path-' . $pathId;
48
                    }
49
                }
50
            }
51
52
            return $tags;
53
        };
54
        $this->getContentInfoKeys = function (ContentInfo $info) {
55
            return [
56
                'ez-content-info-' . $info->id,
57
                'ez-content-info-byRemoteId-' . $this->escapeForCacheKey($info->remoteId),
58
            ];
59
        };
60
61
        $this->getContentTags = function (Content $content) {
62
            $versionInfo = $content->versionInfo;
63
            $tags = [
64
                'content-fields-' . $versionInfo->contentInfo->id,
65
                'content-fields-type-' . $versionInfo->contentInfo->contentTypeId,
66
            ];
67
68
            return $this->getCacheTagsForVersion($versionInfo, $tags);
69
        };
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    public function create(CreateStruct $struct)
76
    {
77
        // Cached on demand when published or loaded
78
        $this->logger->logCall(__METHOD__, ['struct' => $struct]);
79
80
        return $this->persistenceHandler->contentHandler()->create($struct);
81
    }
82
83
    /**
84
     * {@inheritdoc}
85
     */
86
    public function createDraftFromVersion($contentId, $srcVersion, $userId)
87
    {
88
        $this->logger->logCall(__METHOD__, ['content' => $contentId, 'version' => $srcVersion, 'user' => $userId]);
89
        $draft = $this->persistenceHandler->contentHandler()->createDraftFromVersion($contentId, $srcVersion, $userId);
90
        $this->cache->invalidateTags(["content-{$contentId}-version-list"]);
91
92
        return $draft;
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    public function copy($contentId, $versionNo = null, $newOwnerId = null)
99
    {
100
        $this->logger->logCall(__METHOD__, [
101
            'content' => $contentId,
102
            'version' => $versionNo,
103
            'newOwner' => $newOwnerId,
104
        ]);
105
106
        return $this->persistenceHandler->contentHandler()->copy($contentId, $versionNo, $newOwnerId);
107
    }
108
109
    /**
110
     * {@inheritdoc}
111
     */
112
    public function load($contentId, $versionNo = null, array $translations = null)
113
    {
114
        $keySuffix = $versionNo ? "-${versionNo}-" : '-';
115
        $keySuffix .= empty($translations) ? self::ALL_TRANSLATIONS_KEY : implode('|', $translations);
116
117
        return $this->getCacheValue(
118
            (int) $contentId,
119
            'ez-content-',
120
            function ($id) use ($versionNo, $translations) {
121
                return $this->persistenceHandler->contentHandler()->load($id, $versionNo, $translations);
0 ignored issues
show
Bug introduced by
It seems like $translations defined by parameter $translations on line 112 can also be of type array; however, eZ\Publish\SPI\Persistence\Content\Handler::load() does only seem to accept null|array<integer,string>, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
122
            },
123
            $this->getContentTags,
124
            static function (Content $content) use ($keySuffix) {
125
                // Version number & translations is part of keySuffix here and depends on what user asked for
126
                return ['ez-content-' . $content->versionInfo->contentInfo->id . $keySuffix];
127
            },
128
            $keySuffix,
129
            ['content' => $contentId, 'version' => $versionNo, 'translations' => $translations]
130
        );
131
    }
132
133
    public function loadContentList(array $contentIds, array $translations = null): array
134
    {
135
        $keySuffix = '-' . (empty($translations) ? self::ALL_TRANSLATIONS_KEY : implode('|', $translations));
136
137
        return $this->getMultipleCacheValues(
138
            $contentIds,
139
            'ez-content-',
140
            function (array $cacheMissIds) use ($translations) {
141
                return $this->persistenceHandler->contentHandler()->loadContentList($cacheMissIds, $translations);
0 ignored issues
show
Bug introduced by
It seems like $translations defined by parameter $translations on line 133 can also be of type array; however, eZ\Publish\SPI\Persisten...dler::loadContentList() does only seem to accept null|array<integer,string>, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
142
            },
143
            $this->getContentTags,
144
            static function (Content $content) use ($keySuffix) {
145
                // Version number & translations is part of keySuffix here and depends on what user asked for
146
                return ['ez-content-' . $content->versionInfo->contentInfo->id . $keySuffix];
147
            },
148
            $keySuffix,
149
            ['content' => $contentIds, 'translations' => $translations]
150
        );
151
    }
152
153
    /**
154
     * {@inheritdoc}
155
     */
156
    public function loadContentInfo($contentId)
157
    {
158
        return $this->getCacheValue(
159
            $contentId,
160
            'ez-content-info-',
161
            function ($contentId) {
162
                return $this->persistenceHandler->contentHandler()->loadContentInfo($contentId);
163
            },
164
            $this->getContentInfoTags,
165
            $this->getContentInfoKeys,
166
            '',
167
            ['content' => $contentId]
168
        );
169
    }
170
171
    public function loadContentInfoList(array $contentIds)
172
    {
173
        return $this->getMultipleCacheValues(
174
            $contentIds,
175
            'ez-content-info-',
176
            function (array $cacheMissIds) {
177
                return $this->persistenceHandler->contentHandler()->loadContentInfoList($cacheMissIds);
178
            },
179
            $this->getContentInfoTags,
180
            $this->getContentInfoKeys,
181
            '',
182
            ['content' => $contentIds]
183
        );
184
    }
185
186
    /**
187
     * {@inheritdoc}
188
     */
189
    public function loadContentInfoByRemoteId($remoteId)
190
    {
191
        return $this->getCacheValue(
192
            $this->escapeForCacheKey($remoteId),
193
            'ez-content-info-byRemoteId-',
194
            function () use ($remoteId) {
195
                return $this->persistenceHandler->contentHandler()->loadContentInfoByRemoteId($remoteId);
196
            },
197
            $this->getContentInfoTags,
198
            $this->getContentInfoKeys,
199
            '',
200
            ['content' => $remoteId]
201
        );
202
    }
203
204
    /**
205
     * {@inheritdoc}
206
     */
207
    public function loadVersionInfo($contentId, $versionNo = null)
208
    {
209
        $keySuffix = $versionNo ? "-${versionNo}" : '';
210
        $cacheItem = $this->cache->getItem("ez-content-version-info-${contentId}${keySuffix}");
211
        if ($cacheItem->isHit()) {
212
            $this->logger->logCacheHit(['content' => $contentId, 'version' => $versionNo]);
213
214
            return $cacheItem->get();
215
        }
216
217
        $this->logger->logCacheMiss(['content' => $contentId, 'version' => $versionNo]);
218
        $versionInfo = $this->persistenceHandler->contentHandler()->loadVersionInfo($contentId, $versionNo);
219
        $cacheItem->set($versionInfo);
220
        $cacheItem->tag($this->getCacheTagsForVersion($versionInfo));
221
        $this->cache->save($cacheItem);
222
223
        return $versionInfo;
224
    }
225
226
    /**
227
     * {@inheritdoc}
228
     */
229
    public function loadDraftsForUser($userId)
230
    {
231
        $this->logger->logCall(__METHOD__, ['user' => $userId]);
232
233
        return $this->persistenceHandler->contentHandler()->loadDraftsForUser($userId);
234
    }
235
236
    /**
237
     * {@inheritdoc}
238
     */
239
    public function setStatus($contentId, $status, $versionNo)
240
    {
241
        $this->logger->logCall(__METHOD__, ['content' => $contentId, 'status' => $status, 'version' => $versionNo]);
242
        $return = $this->persistenceHandler->contentHandler()->setStatus($contentId, $status, $versionNo);
243
244
        if ($status === VersionInfo::STATUS_PUBLISHED) {
245
            $this->cache->invalidateTags(['content-' . $contentId]);
246
        } else {
247
            $this->cache->invalidateTags(["content-{$contentId}-version-{$versionNo}"]);
248
        }
249
250
        return $return;
251
    }
252
253
    /**
254
     * {@inheritdoc}
255
     */
256
    public function updateMetadata($contentId, MetadataUpdateStruct $struct)
257
    {
258
        $this->logger->logCall(__METHOD__, ['content' => $contentId, 'struct' => $struct]);
259
        $contentInfo = $this->persistenceHandler->contentHandler()->updateMetadata($contentId, $struct);
260
        $this->cache->invalidateTags(['content-' . $contentId]);
261
262
        return $contentInfo;
263
    }
264
265
    /**
266
     * {@inheritdoc}
267
     */
268
    public function updateContent($contentId, $versionNo, UpdateStruct $struct)
269
    {
270
        $this->logger->logCall(__METHOD__, ['content' => $contentId, 'version' => $versionNo, 'struct' => $struct]);
271
        $content = $this->persistenceHandler->contentHandler()->updateContent($contentId, $versionNo, $struct);
272
        $this->cache->invalidateTags(["content-{$contentId}-version-{$versionNo}"]);
273
274
        return $content;
275
    }
276
277
    /**
278
     * {@inheritdoc}
279
     */
280
    public function deleteContent($contentId)
281
    {
282
        $this->logger->logCall(__METHOD__, ['content' => $contentId]);
283
284
        // Load reverse field relations first
285
        $reverseRelations = $this->persistenceHandler->contentHandler()->loadReverseRelations(
286
            $contentId,
287
            APIRelation::FIELD | APIRelation::ASSET
288
        );
289
290
        $return = $this->persistenceHandler->contentHandler()->deleteContent($contentId);
291
292
        if (!empty($reverseRelations)) {
293
            $tags = \array_map(
294
                static function ($relation) {
295
                    // only the full content object *with* fields is affected by this
296
                    return 'content-fields-' . $relation->sourceContentId;
297
                },
298
                $reverseRelations
299
            );
300
        } else {
301
            $tags = [];
302
        }
303
        $tags[] = 'content-' . $contentId;
304
        $this->cache->invalidateTags($tags);
305
306
        return $return;
307
    }
308
309
    /**
310
     * {@inheritdoc}
311
     */
312
    public function deleteVersion($contentId, $versionNo)
313
    {
314
        $this->logger->logCall(__METHOD__, ['content' => $contentId, 'version' => $versionNo]);
315
        $return = $this->persistenceHandler->contentHandler()->deleteVersion($contentId, $versionNo);
316
        $this->cache->invalidateTags(["content-{$contentId}-version-{$versionNo}"]);
317
318
        return $return;
319
    }
320
321
    /**
322
     * {@inheritdoc}
323
     */
324
    public function listVersions($contentId, $status = null, $limit = -1)
325
    {
326
        $cacheItem = $this->cache->getItem("ez-content-${contentId}-version-list" . ($status ? "-byStatus-${status}" : '') . "-limit-{$limit}");
327
        if ($cacheItem->isHit()) {
328
            $this->logger->logCacheHit(['content' => $contentId, 'status' => $status]);
329
330
            return $cacheItem->get();
331
        }
332
333
        $this->logger->logCacheMiss(['content' => $contentId, 'status' => $status]);
334
        $versions = $this->persistenceHandler->contentHandler()->listVersions($contentId, $status, $limit);
335
        $cacheItem->set($versions);
336
        $tags = ["content-{$contentId}", "content-{$contentId}-version-list"];
337
        foreach ($versions as $version) {
338
            $tags = $this->getCacheTagsForVersion($version, $tags);
339
        }
340
        $cacheItem->tag($tags);
341
        $this->cache->save($cacheItem);
342
343
        return $versions;
344
    }
345
346
    /**
347
     * {@inheritdoc}
348
     */
349
    public function addRelation(RelationCreateStruct $relation)
350
    {
351
        $this->logger->logCall(__METHOD__, ['struct' => $relation]);
352
353
        return $this->persistenceHandler->contentHandler()->addRelation($relation);
354
    }
355
356
    /**
357
     * {@inheritdoc}
358
     */
359
    public function removeRelation($relationId, $type)
360
    {
361
        $this->logger->logCall(__METHOD__, ['relation' => $relationId, 'type' => $type]);
362
        $this->persistenceHandler->contentHandler()->removeRelation($relationId, $type);
363
    }
364
365
    /**
366
     * {@inheritdoc}
367
     */
368
    public function loadRelations($sourceContentId, $sourceContentVersionNo = null, $type = null)
369
    {
370
        $this->logger->logCall(
371
            __METHOD__,
372
            [
373
                'content' => $sourceContentId,
374
                'version' => $sourceContentVersionNo,
375
                'type' => $type,
376
            ]
377
        );
378
379
        return $this->persistenceHandler->contentHandler()->loadRelations($sourceContentId, $sourceContentVersionNo, $type);
380
    }
381
382
    /**
383
     * {@inheritdoc}
384
     */
385
    public function countReverseRelations(int $destinationContentId, ?int $type = null): int
386
    {
387
        $this->logger->logCall(__METHOD__, ['content' => $destinationContentId, 'type' => $type]);
388
389
        return $this->persistenceHandler->contentHandler()->countReverseRelations($destinationContentId, $type);
390
    }
391
392
    /**
393
     * {@inheritdoc}
394
     */
395
    public function loadReverseRelations($destinationContentId, $type = null)
396
    {
397
        $this->logger->logCall(__METHOD__, ['content' => $destinationContentId, 'type' => $type]);
398
399
        return $this->persistenceHandler->contentHandler()->loadReverseRelations($destinationContentId, $type);
400
    }
401
402
    /**
403
     * {@inheritdoc}
404
     */
405
    public function publish($contentId, $versionNo, MetadataUpdateStruct $struct)
406
    {
407
        $this->logger->logCall(__METHOD__, ['content' => $contentId, 'version' => $versionNo, 'struct' => $struct]);
408
        $content = $this->persistenceHandler->contentHandler()->publish($contentId, $versionNo, $struct);
409
        $this->cache->invalidateTags(['content-' . $contentId]);
410
411
        return $content;
412
    }
413
414
    /**
415
     * {@inheritdoc}
416
     */
417
    public function removeTranslationFromContent($contentId, $languageCode)
418
    {
419
        $this->deleteTranslationFromContent($contentId, $languageCode);
420
    }
421
422
    /**
423
     * {@inheritdoc}
424
     */
425
    public function deleteTranslationFromContent($contentId, $languageCode)
426
    {
427
        $this->logger->logCall(
428
            __METHOD__,
429
            [
430
                'contentId' => $contentId,
431
                'languageCode' => $languageCode,
432
            ]
433
        );
434
435
        $this->persistenceHandler->contentHandler()->deleteTranslationFromContent($contentId, $languageCode);
436
        $this->cache->invalidateTags(['content-' . $contentId]);
437
    }
438
439
    /**
440
     * {@inheritdoc}
441
     */
442
    public function deleteTranslationFromDraft($contentId, $versionNo, $languageCode)
443
    {
444
        $this->logger->logCall(
445
            __METHOD__,
446
            ['content' => $contentId, 'version' => $versionNo, 'languageCode' => $languageCode]
447
        );
448
        $content = $this->persistenceHandler->contentHandler()->deleteTranslationFromDraft(
449
            $contentId,
450
            $versionNo,
451
            $languageCode
452
        );
453
        $this->cache->invalidateTags(["content-{$contentId}-version-{$versionNo}"]);
454
455
        return $content;
456
    }
457
458
    /**
459
     * Return relevant content and location tags so cache can be purged reliably.
460
     *
461
     * For use when generating cache, not on invalidation.
462
     *
463
     * @param \eZ\Publish\SPI\Persistence\Content\VersionInfo $versionInfo
464
     * @param array $tags Optional, can be used to specify other tags.
465
     *
466
     * @return array
467
     */
468
    private function getCacheTagsForVersion(VersionInfo $versionInfo, array $tags = []): array
469
    {
470
        $contentInfo = $versionInfo->contentInfo;
471
        $tags[] = 'content-' . $contentInfo->id . '-version-' . $versionInfo->versionNo;
472
        $getContentInfoTagsFn = $this->getContentInfoTags;
473
474
        return $getContentInfoTagsFn($contentInfo, $tags);
475
    }
476
477
    private function getCacheTagsForContent(Content $content): array
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
478
    {
479
        $versionInfo = $content->versionInfo;
480
        $tags = [
481
            'content-fields-' . $versionInfo->contentInfo->id,
482
            'content-fields-type-' . $versionInfo->contentInfo->contentTypeId,
483
        ];
484
485
        return $this->getCacheTagsForVersion($versionInfo, $tags);
486
    }
487
}
488