Completed
Push — master ( 7bc8ae...9f2037 )
by Łukasz
21:21
created

LocationHandler::init()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 1
nop 0
dl 0
loc 22
rs 9.568
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * File containing the LocationHandler 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\SPI\Persistence\Content\Location\Handler as LocationHandlerInterface;
12
use eZ\Publish\SPI\Persistence\Content\Location\CreateStruct;
13
use eZ\Publish\SPI\Persistence\Content\Location\UpdateStruct;
14
use eZ\Publish\SPI\Persistence\Content\Location;
15
16
/**
17
 * @see \eZ\Publish\SPI\Persistence\Content\Location\Handler
18
 */
19
class LocationHandler extends AbstractInMemoryPersistenceHandler implements LocationHandlerInterface
20
{
21
    /**
22
     * @var callable
23
     */
24
    private $getLocationTags;
25
26
    /**
27
     * @var callable
28
     */
29
    private $getLocationKeys;
30
31
    protected function init(): void
32
    {
33
        $this->getLocationTags = static function (Location $location) {
34
            $tags = [
35
                 'content-' . $location->contentId,
36
                 'location-' . $location->id,
37
                 'location-data-' . $location->id,
38
             ];
39
            foreach (\explode('/', \trim($location->pathString, '/')) as $pathId) {
40
                $tags[] = 'location-path-' . $pathId;
41
                $tags[] = 'location-path-data-' . $pathId;
42
            }
43
44
            return $tags;
45
        };
46
        $this->getLocationKeys = function (Location $location, $keySuffix = '-1') {
47
            return [
48
                 'ez-location-' . $location->id . $keySuffix,
49
                 'ez-location-remoteid-' . $this->escapeForCacheKey($location->remoteId) . $keySuffix,
50
             ];
51
        };
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57 View Code Duplication
    public function load($locationId, array $translations = null, bool $useAlwaysAvailable = true)
58
    {
59
        $keySuffix = '-' . $this->getCacheTranslationKey($translations, $useAlwaysAvailable);
60
        $getLocationKeysFn = $this->getLocationKeys;
61
62
        return $this->getCacheValue(
63
            (int) $locationId,
64
            'ez-location-',
65
            function ($id) use ($translations, $useAlwaysAvailable) {
66
                return $this->persistenceHandler->locationHandler()->load($id, $translations, $useAlwaysAvailable);
0 ignored issues
show
Bug introduced by
It seems like $translations defined by parameter $translations on line 57 can also be of type array; however, eZ\Publish\SPI\Persisten...ocation\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...
67
            },
68
            $this->getLocationTags,
69
            static function (Location $location) use ($keySuffix, $getLocationKeysFn) {
70
                return $getLocationKeysFn($location, $keySuffix);
71
            },
72
            $keySuffix,
73
            ['location' => $locationId, 'translations' => $translations, 'alwaysAvailable' => $useAlwaysAvailable]
74
        );
75
    }
76
77 View Code Duplication
    public function loadList(array $locationIds, array $translations = null, bool $useAlwaysAvailable = true): iterable
78
    {
79
        $keySuffix = '-' . $this->getCacheTranslationKey($translations, $useAlwaysAvailable);
80
        $getLocationKeysFn = $this->getLocationKeys;
81
82
        return $this->getMultipleCacheValues(
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getMultipl... $useAlwaysAvailable)); (array) is incompatible with the return type declared by the interface eZ\Publish\SPI\Persisten...ation\Handler::loadList of type eZ\Publish\SPI\Persisten...ntent\Location\iterable.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
83
            $locationIds,
84
            'ez-location-',
85
            function (array $ids) use ($translations, $useAlwaysAvailable) {
86
                return $this->persistenceHandler->locationHandler()->loadList($ids, $translations, $useAlwaysAvailable);
0 ignored issues
show
Bug introduced by
It seems like $translations defined by parameter $translations on line 77 can also be of type array; however, eZ\Publish\SPI\Persisten...ion\Handler::loadList() 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...
87
            },
88
            $this->getLocationTags,
89
            static function (Location $location) use ($keySuffix, $getLocationKeysFn) {
90
                return $getLocationKeysFn($location, $keySuffix);
91
            },
92
            $keySuffix,
93
            ['location' => $locationIds, 'translations' => $translations, 'alwaysAvailable' => $useAlwaysAvailable]
94
        );
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    public function loadSubtreeIds($locationId)
101
    {
102
        $cacheItem = $this->cache->getItem("ez-location-subtree-${locationId}");
103
        if ($cacheItem->isHit()) {
104
            $this->logger->logCacheHit(['location' => $locationId]);
105
106
            return $cacheItem->get();
107
        }
108
109
        $this->logger->logCacheMiss(['location' => $locationId]);
110
        $locationIds = $this->persistenceHandler->locationHandler()->loadSubtreeIds($locationId);
111
112
        $cacheItem->set($locationIds);
113
        $cacheTags = ['location-' . $locationId, 'location-path-' . $locationId];
114
        foreach ($locationIds as $id) {
115
            $cacheTags[] = 'location-' . $id;
116
            $cacheTags[] = 'location-path-' . $id;
117
        }
118
        $cacheItem->tag($cacheTags);
119
        $this->cache->save($cacheItem);
120
121
        return $locationIds;
122
    }
123
124
    /**
125
     * {@inheritdoc}
126
     */
127
    public function loadLocationsByContent($contentId, $rootLocationId = null)
128
    {
129
        if ($rootLocationId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $rootLocationId of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. 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 integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
130
            $cacheItem = $this->cache->getItem("ez-content-locations-${contentId}-root-${rootLocationId}");
131
            $cacheTags = ['content-' . $contentId, 'location-' . $rootLocationId, 'location-path-' . $rootLocationId];
132
        } else {
133
            $cacheItem = $this->cache->getItem("ez-content-locations-${contentId}");
134
            $cacheTags = ['content-' . $contentId];
135
        }
136
137
        if ($cacheItem->isHit()) {
138
            $this->logger->logCacheHit(['content' => $contentId, 'root' => $rootLocationId]);
139
140
            return $cacheItem->get();
141
        }
142
143
        $this->logger->logCacheMiss(['content' => $contentId, 'root' => $rootLocationId]);
144
        $locations = $this->persistenceHandler->locationHandler()->loadLocationsByContent($contentId, $rootLocationId);
145
146
        $cacheItem->set($locations);
147
        foreach ($locations as $location) {
148
            $cacheTags = $this->getCacheTags($location, $cacheTags);
149
        }
150
        $cacheItem->tag($cacheTags);
151
        $this->cache->save($cacheItem);
152
153
        return $locations;
154
    }
155
156
    /**
157
     * {@inheritdoc}
158
     */
159
    public function loadParentLocationsForDraftContent($contentId)
160
    {
161
        $cacheItem = $this->cache->getItem("ez-content-locations-${contentId}-parentForDraft");
162
        if ($cacheItem->isHit()) {
163
            $this->logger->logCacheHit(['content' => $contentId]);
164
165
            return $cacheItem->get();
166
        }
167
168
        $this->logger->logCacheMiss(['content' => $contentId]);
169
        $locations = $this->persistenceHandler->locationHandler()->loadParentLocationsForDraftContent($contentId);
170
171
        $cacheItem->set($locations);
172
        $cacheTags = ['content-' . $contentId];
173
        foreach ($locations as $location) {
174
            $cacheTags = $this->getCacheTags($location, $cacheTags);
175
        }
176
        $cacheItem->tag($cacheTags);
177
        $this->cache->save($cacheItem);
178
179
        return $locations;
180
    }
181
182
    /**
183
     * {@inheritdoc}
184
     */
185 View Code Duplication
    public function loadByRemoteId($remoteId, array $translations = null, bool $useAlwaysAvailable = true)
186
    {
187
        $keySuffix = '-' . $this->getCacheTranslationKey($translations, $useAlwaysAvailable);
188
        $getLocationKeysFn = $this->getLocationKeys;
189
190
        return $this->getCacheValue(
191
            $this->escapeForCacheKey($remoteId),
192
            'ez-location-remoteid-',
193
            function () use ($remoteId, $translations, $useAlwaysAvailable) {
194
                return $this->persistenceHandler->locationHandler()->loadByRemoteId($remoteId, $translations, $useAlwaysAvailable);
0 ignored issues
show
Bug introduced by
It seems like $translations defined by parameter $translations on line 185 can also be of type array; however, eZ\Publish\SPI\Persisten...ndler::loadByRemoteId() 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...
195
            },
196
            $this->getLocationTags,
197
            static function (Location $location) use ($keySuffix, $getLocationKeysFn) {
198
                return $getLocationKeysFn($location, $keySuffix);
199
            },
200
            $keySuffix,
201
            ['location' => $remoteId, 'translations' => $translations, 'alwaysAvailable' => $useAlwaysAvailable]
202
        );
203
    }
204
205
    /**
206
     * {@inheritdoc}
207
     */
208 View Code Duplication
    public function copySubtree($sourceId, $destinationParentId, $newOwnerId = null)
209
    {
210
        $this->logger->logCall(__METHOD__, array(
211
            'source' => $sourceId,
212
            'destination' => $destinationParentId,
213
            'newOwner' => $newOwnerId,
214
        ));
215
216
        return $this->persistenceHandler->locationHandler()->copySubtree($sourceId, $destinationParentId, $newOwnerId);
217
    }
218
219
    /**
220
     * {@inheritdoc}
221
     */
222 View Code Duplication
    public function move($sourceId, $destinationParentId)
223
    {
224
        $this->logger->logCall(__METHOD__, array('source' => $sourceId, 'destination' => $destinationParentId));
225
        $return = $this->persistenceHandler->locationHandler()->move($sourceId, $destinationParentId);
226
227
        $this->cache->invalidateTags(['location-path-' . $sourceId]);
228
229
        return $return;
230
    }
231
232
    /**
233
     * {@inheritdoc}
234
     */
235
    public function markSubtreeModified($locationId, $timestamp = null)
236
    {
237
        $this->logger->logCall(__METHOD__, array('location' => $locationId, 'time' => $timestamp));
238
        $this->persistenceHandler->locationHandler()->markSubtreeModified($locationId, $timestamp);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\SPI\Persisten...::markSubtreeModified() has been deprecated with message: As of 6.8, not been used by repository since 5.x.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
239
    }
240
241
    /**
242
     * {@inheritdoc}
243
     */
244 View Code Duplication
    public function hide($locationId)
245
    {
246
        $this->logger->logCall(__METHOD__, array('location' => $locationId));
247
        $return = $this->persistenceHandler->locationHandler()->hide($locationId);
248
249
        $this->cache->invalidateTags(['location-path-data-' . $locationId]);
250
251
        return $return;
252
    }
253
254
    /**
255
     * {@inheritdoc}
256
     */
257
    public function unHide($locationId)
258
    {
259
        $this->logger->logCall(__METHOD__, array('location' => $locationId));
260
        $return = $this->persistenceHandler->locationHandler()->unHide($locationId);
261
262
        $this->cache->invalidateTags(['location-path-data-' . $locationId]);
263
264
        return $return;
265
    }
266
267
    /**
268
     * Sets a location + all children to invisible.
269
     *
270
     * @param int $id Location ID
271
     */
272
    public function setInvisible(int $id): void
273
    {
274
        $this->logger->logCall(__METHOD__, ['location' => $id]);
275
        $this->persistenceHandler->locationHandler()->setInvisible($id);
276
277
        $this->cache->invalidateTags(['location-path-data-' . $id]);
278
    }
279
280
    /**
281
     * Sets a location + all children to visible.
282
     *
283
     * @param int $id Location ID
284
     */
285
    public function setVisible(int $id): void
286
    {
287
        $this->logger->logCall(__METHOD__, ['location' => $id]);
288
        $this->persistenceHandler->locationHandler()->setVisible($id);
289
290
        $this->cache->invalidateTags(['location-path-data-' . $id]);
291
    }
292
293
    /**
294
     * {@inheritdoc}
295
     */
296
    public function swap($locationId1, $locationId2)
297
    {
298
        $this->logger->logCall(__METHOD__, array('location1' => $locationId1, 'location2' => $locationId2));
299
        $locationHandler = $this->persistenceHandler->locationHandler();
300
301
        $return = $locationHandler->swap($locationId1, $locationId2);
302
303
        $this->cache->invalidateTags(
304
            [
305
                'location-' . $locationId1,
306
                'location-' . $locationId2,
307
            ]
308
        );
309
310
        return $return;
311
    }
312
313
    /**
314
     * {@inheritdoc}
315
     */
316
    public function update(UpdateStruct $struct, $locationId)
317
    {
318
        $this->logger->logCall(__METHOD__, array('location' => $locationId, 'struct' => $struct));
319
        $this->persistenceHandler->locationHandler()->update($struct, $locationId);
320
321
        $this->cache->invalidateTags(['location-data-' . $locationId]);
322
    }
323
324
    /**
325
     * {@inheritdoc}
326
     */
327
    public function create(CreateStruct $locationStruct)
328
    {
329
        $this->logger->logCall(__METHOD__, array('struct' => $locationStruct));
330
        $location = $this->persistenceHandler->locationHandler()->create($locationStruct);
331
332
        // need to clear loadLocationsByContent and similar collections involving locations data
333
        // also need to clear content info on main location changes
334
        $this->cache->invalidateTags(['content-' . $locationStruct->contentId, 'role-assignment-group-list-' . $locationStruct->contentId]);
335
336
        return $location;
337
    }
338
339
    /**
340
     * {@inheritdoc}
341
     */
342
    public function removeSubtree($locationId)
343
    {
344
        $this->logger->logCall(__METHOD__, array('location' => $locationId));
345
        $return = $this->persistenceHandler->locationHandler()->removeSubtree($locationId);
346
347
        $this->cache->invalidateTags(['location-path-' . $locationId]);
348
349
        return $return;
350
    }
351
352
    /**
353
     * {@inheritdoc}
354
     */
355
    public function setSectionForSubtree($locationId, $sectionId)
356
    {
357
        $this->logger->logCall(__METHOD__, array('location' => $locationId, 'section' => $sectionId));
358
        $this->persistenceHandler->locationHandler()->setSectionForSubtree($locationId, $sectionId);
359
360
        $this->cache->invalidateTags(['location-path-' . $locationId]);
361
    }
362
363
    /**
364
     * {@inheritdoc}
365
     */
366
    public function changeMainLocation($contentId, $locationId)
367
    {
368
        $this->logger->logCall(__METHOD__, array('location' => $locationId, 'content' => $contentId));
369
        $this->persistenceHandler->locationHandler()->changeMainLocation($contentId, $locationId);
370
371
        $this->cache->invalidateTags(['content-' . $contentId]);
372
    }
373
374
    /**
375
     * Get the total number of all existing Locations. Can be combined with loadAllLocations.
376
     *
377
     * @return int
378
     */
379
    public function countAllLocations()
380
    {
381
        $this->logger->logCall(__METHOD__);
382
383
        return $this->persistenceHandler->locationHandler()->countAllLocations();
384
    }
385
386
    /**
387
     * Bulk-load all existing Locations, constrained by $limit and $offset to paginate results.
388
     *
389
     * @param int $offset
390
     * @param int $limit
391
     *
392
     * @return \eZ\Publish\SPI\Persistence\Content\Location[]
393
     */
394
    public function loadAllLocations($offset, $limit)
395
    {
396
        $this->logger->logCall(__METHOD__, array('offset' => $offset, 'limit' => $limit));
397
398
        return $this->persistenceHandler->locationHandler()->loadAllLocations($offset, $limit);
399
    }
400
401
    /**
402
     * Return relevant content and location tags so cache can be purged reliably.
403
     *
404
     * @param \eZ\Publish\SPI\Persistence\Content\Location $location
405
     * @param array $tags Optional, can be used to specify additional tags.
406
     *
407
     * @return array
408
     */
409
    private function getCacheTags(Location $location, $tags = [])
410
    {
411
        $tags[] = 'content-' . $location->contentId;
412
        $tags[] = 'location-' . $location->id;
413
        $tags[] = 'location-data-' . $location->id;
414
        foreach (explode('/', trim($location->pathString, '/')) as $pathId) {
415
            $tags[] = 'location-path-' . $pathId;
416
            $tags[] = 'location-path-data-' . $pathId;
417
        }
418
419
        return $tags;
420
    }
421
422
    private function getCacheTranslationKey(array $translations = null, bool $useAlwaysAvailable = true): string
423
    {
424
        if (empty($translations)) {
425
            return (int)$useAlwaysAvailable;
426
        }
427
428
        // Sort array as we don't care about order in location handler usage & want to optimize for cache hits.
429
        sort($translations);
430
431
        return implode('|', $translations) . '|' . (int)$useAlwaysAvailable;
432
    }
433
}
434