Completed
Push — 9.x ( 6043ef...c82ffe )
by Tim
07:16
created

GenericCacheAdapter   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 228
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 20
lcom 1
cbo 2
dl 0
loc 228
ccs 0
cts 78
cp 0
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A cacheKey() 0 4 1
A isCached() 0 11 2
A notCached() 0 4 1
A addReference() 0 4 1
A resolveReference() 0 11 2
A toCache() 0 20 4
A fromCache() 0 4 1
A flushCache() 0 14 2
A raiseCounter() 0 18 2
A mergeAttributesRecursive() 0 18 3
1
<?php
2
3
/**
4
 * TechDivision\Import\Cache\GenericCacheAdapter
5
 *
6
 * NOTICE OF LICENSE
7
 *
8
 * This source file is subject to the Open Software License (OSL 3.0)
9
 * that is available through the world-wide-web at this URL:
10
 * http://opensource.org/licenses/osl-3.0.php
11
 *
12
 * PHP version 5
13
 *
14
 * @author    Tim Wagner <[email protected]>
15
 * @copyright 2019 TechDivision GmbH <[email protected]>
16
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
17
 * @link      https://github.com/techdivision/import
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Cache;
22
23
use Psr\Cache\CacheItemPoolInterface;
24
25
/**
26
 * Generic cache adapter implementation.
27
 *
28
 * @author    Tim Wagner <[email protected]>
29
 * @copyright 2019 TechDivision GmbH <[email protected]>
30
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
31
 * @link      https://github.com/techdivision/import
32
 * @link      http://www.techdivision.com
33
 */
34
class GenericCacheAdapter implements CacheAdapterInterface
35
{
36
37
    /**
38
     * The cache for the query results.
39
     *
40
     * @var \Psr\Cache\CacheItemPoolInterface
41
     */
42
    protected $cache;
43
44
    /**
45
     * References that links to another cache entry.
46
     *
47
     * @var array
48
     */
49
    protected $references = array();
50
51
    /**
52
     * Initialize the cache handler with the passed cache and configuration instances.
53
     * .
54
     * @param \Psr\Cache\CacheItemPoolInterface           $cache         The cache instance
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter type; 11 found
Loading history...
Coding Style introduced by
Expected 1 spaces after parameter name; 9 found
Loading history...
55
     */
56
    public function __construct(CacheItemPoolInterface $cache)
57
    {
58
        $this->cache = $cache;
59
    }
60
61
    /**
62
     * Prepares a unique cache key for the passed query name and params.
63
     *
64
     * @param string $uniqueName A unique name used to prepare the cache key with
65
     * @param array  $params     The query params
66
     *
67
     * @return string The prepared cache key
68
     */
69
    public function cacheKey($uniqueName, array $params)
70
    {
71
        return sprintf('%s-%s', $uniqueName, implode('-', $params));
72
    }
73
74
    /**
75
     * Query whether or not a cache value for the passed cache key is available.
76
     *
77
     * @param string $key The cache key to query for
78
     *
79
     * @return boolean TRUE if the a value is available, else FALSE
80
     */
81
    public function isCached($key)
82
    {
83
84
        // query whether or not the item has been cached, and if yes if the cache is valid
85
        if ($this->cache->hasItem($resolvedKey = $this->resolveReference($key))) {
86
            return $this->cache->getItem($resolvedKey)->isHit();
87
        }
88
89
        // return FALSE in all other cases
90
        return false;
91
    }
92
93
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $key should have a doc-comment as per coding-style.
Loading history...
94
     * Inversion of the isCached() method.
95
     *
96
     * @param string $cacheKey The cache key to query for
0 ignored issues
show
Bug introduced by
There is no parameter named $cacheKey. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
Coding Style introduced by
Doc comment for parameter $cacheKey does not match actual variable name $key
Loading history...
97
     *
98
     * @return boolean TRUE if the value is not available, else FALSE
99
     */
100
    public function notCached($key)
101
    {
102
        return !$this->isCached($key);
103
    }
104
105
    /**
106
     * Add's a cache reference from one key to another.
107
     *
108
     * @param string $from The key to reference from
109
     * @param string $to   The key to reference to
110
     *
111
     * @return void
112
     */
113
    public function addReference($from, $to)
114
    {
115
        $this->references[$from] = $to;
116
    }
117
118
    /**
119
     * Resolve's the cache key.
120
     *
121
     * @param string $from The cache key to resolve
122
     *
123
     * @return string The resolved reference
124
     */
125
    protected function resolveReference($from)
126
    {
127
128
        // query whether or not a reference exists
129
        if (isset($this->references[$from])) {
130
            return $this->references[$from];
131
        }
132
133
        // return the passed reference
134
        return $from;
135
    }
136
137
    /**
138
     * Add the passed item to the cache.
139
     *
140
     * @param string  $key        The cache key to use
141
     * @param mixed   $value      The value that has to be cached
142
     * @param array   $references An array with references to add
143
     * @param boolean $override   Flag that allows to override an exising cache entry
144
     *
145
     * @return void
146
     */
147
    public function toCache($key, $value, array $references = array(), $override = false)
148
    {
149
150
        // query whether or not the key has already been used
151
        if ($this->isCached($key) && $override === false) {
152
            throw new \Exception(sprintf('Try to override data with key %s', $key));
153
        }
154
155
        // initialize the cache item
156
        $cacheItem = $this->cache->getItem($key);
157
        $cacheItem->set($value);
158
159
        // set the attribute in the registry
160
        $this->cache->save($cacheItem);
161
162
        // also register the references if given
163
        foreach ($references as $from => $to) {
164
            $this->references[$from] = $to;
165
        }
166
    }
167
168
    /**
169
     * Returns a new cache item for the passed key
170
     *
171
     * @param string $key The cache key to return the item for
172
     *
173
     * @return mixed The value for the passed key
174
     */
175
    public function fromCache($key)
176
    {
177
        return $this->cache->getItem($this->resolveReference($key))->get();
178
    }
179
180
    /**
181
     * Flush the cache, or the value with the passed key.
182
     *
183
     * @param mixed|null $key The key of the value to flush
184
     *
185
     * @return void
186
     */
187
    public function flushCache($key = null)
188
    {
189
190
        // flush the complete cache, if NO cache key has been passed
191
        if ($key == null) {
192
            $this->cache->clear();
193
            $this->references = array();
194
            return;
195
        }
196
197
        // only flush the value with the passed cache key, also remove the reference
198
        $this->cache->deleteItem($this->resolveReference($key));
199
        unset($this->references[$key]);
200
    }
201
202
    /**
203
     * Raises the value for the attribute with the passed key by one.
204
     *
205
     * @param mixed $key         The key of the attribute to raise the value for
206
     * @param mixed $counterName The name of the counter to raise
207
     *
208
     * @return integer The counter's new value
209
     */
210
    public function raiseCounter($key, $counterName)
211
    {
212
213
        // initialize the counter
214
        $counter = 0;
215
216
        // raise/initialize the value
217
        if ($this->isCached($key)) {
218
            $value = $this->fromCache($key);
219
            $counter = $value[$counterName];
220
        }
221
222
        // set the counter value back to the cache item/cache
223
        $this->toCache($key, array($counterName => ++$counter), array(), true);
224
225
        // return the new value
226
        return $counter;
227
    }
228
229
    /**
230
     * This method merges the passed attributes with an array that
231
     * has already been added under the passed key.
232
     *
233
     * If no value will be found under the passed key, the attributes
234
     * will simply be registered.
235
     *
236
     * @param mixed $key        The key of the attributes that has to be merged with the passed ones
237
     * @param array $attributes The attributes that has to be merged with the exising ones
238
     *
239
     * @return void
240
     * @throws \Exception Is thrown, if the already registered value is no array
241
     * @link http://php.net/array_replace_recursive
242
     */
243
    public function mergeAttributesRecursive($key, array $attributes)
244
    {
245
246
        // if the key not exists, simply add the new attributes
247
        if ($this->notCached($key)) {
248
            $this->toCache($key, $attributes);
249
            return;
250
        }
251
252
        // if the key exists and the value is an array, merge it with the passed array
253
        if (is_array($value = $this->fromCache($key))) {
254
            $this->toCache($key, array_replace_recursive($value, $attributes), array(), true);
255
            return;
256
        }
257
258
        // throw an exception if the key exists, but the found value is not of type array
259
        throw new \Exception(sprintf('Can\'t merge attributes, because value for key %s already exists, but is not of type array', $key));
260
    }
261
}
262