Completed
Push — inmemory-abstract-trait ( 124d36 )
by André
26:24 queued 03:39
created

AbstractTrait::getMultipleCacheValues()   B

Complexity

Conditions 8
Paths 25

Size

Total Lines 60

Duplication

Lines 27
Ratio 45 %

Importance

Changes 0
Metric Value
cc 8
nc 25
nop 5
dl 27
loc 60
rs 7.6282
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * File containing the AbstractTrait.
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
/**
12
 * Trait AbstractTrait.
13
 *
14
 * @internal Only for use within this namespace.
15
 *
16
 * @property \Symfony\Component\Cache\Adapter\TagAwareAdapterInterface $cache
17
 */
18
trait AbstractTrait
19
{
20
    /**
21
     * @var \eZ\Publish\Core\Persistence\Cache\PersistenceLogger
22
     */
23
    protected $logger;
24
25
    /**
26
     * Helper for getting multiple cache items in one call and do the id extraction for you.
27
     *
28
     * Cache items must be stored with a key in the following format "${keyPrefix}${id}", like "ez-content-info-${id}",
29
     * in order for this method to be able to prefix key on id's and also extract key prefix afterwards.
30
     *
31
     * @param array $ids
32
     * @param string $keyPrefix E.g "ez-content-"
33
     * @param callable $backendLoader Function for loading missing objects, gets array with missing id's as argument,
34
     *                                expects return value to be array with id as key. Missing items should be missing.
35
     * @param callable $cacheTagger Function for tagging loaded object, gets object as argument, return array of tags.
36
     * @param string $keySuffix Optional, e.g "-by-identifier"
37
     *
38
     * @return array
39
     */
40
    final protected function getMultipleCacheValues(
41
        array $ids,
42
        string $keyPrefix,
43
        callable $backendLoader,
44
        callable $cacheTagger,
45
        string $keySuffix = ''
46
    ): array {
47
        if (empty($ids)) {
48
            return [];
49
        }
50
51
        // Generate unique cache keys
52
        $cacheKeys = [];
53
         $cacheKeysToIdMap = [];
54 View Code Duplication
        foreach (\array_unique($ids) as $id) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
55
            $key = $keyPrefix . $id . $keySuffix;
56
            $cacheKeys[] = $key;
57
            $cacheKeysToIdMap[$key] = $id;
58
        }
59
60
        // Load cache items by cache keys (will contain hits and misses)
61
        $list = [];
62
        $cacheMisses = [];
63 View Code Duplication
        foreach ($this->cache->getItems($cacheKeys) as $key => $cacheItem) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
64
            $id = $cacheKeysToIdMap[$key];
65
            if ($cacheItem->isHit()) {
66
                $list[$id] = $cacheItem->get();
67
            } else {
68
                $cacheMisses[] = $id;
69
                $list[$id] = $cacheItem;
70
            }
71
        }
72
73
        // No misses, return completely cached list
74
        if (empty($cacheMisses)) {
75
            $this->logger->logCacheHit($ids, 3);
76
77
            return $list;
78
        }
79
80
        // Load missing items, save to cache & apply to list if found
81
        $backendLoadedList = $backendLoader($cacheMisses);
82 View Code Duplication
        foreach ($cacheMisses as $id) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
83
            if (isset($backendLoadedList[$id])) {
84
                $this->cache->save(
85
                    $list[$id]
86
                        ->set($backendLoadedList[$id])
87
                        ->tag($cacheTagger($backendLoadedList[$id]))
88
                );
89
                $list[$id] = $backendLoadedList[$id];
90
            } else {
91
                // not found
92
                unset($list[$id]);
93
            }
94
        }
95
96
        $this->logger->logCacheMiss($cacheMisses, 3);
97
98
        return $list;
99
    }
100
}
101