Completed
Push — v5.1 ( dd3c74...620699 )
by Georges
05:19 queued 02:39
created

CacheItemPoolTrait   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 234
Duplicated Lines 4.27 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 5
Bugs 3 Features 1
Metric Value
c 5
b 3
f 1
dl 10
loc 234
rs 9.6
wmc 32
lcom 1
cbo 5

10 Methods

Rating   Name   Duplication   Size   Complexity  
B getItem() 0 55 9
A setItem() 0 10 2
A getItems() 0 9 2
A hasItem() 0 6 1
A clear() 0 7 1
A deleteItem() 0 17 3
A deleteItems() 0 12 3
B save() 5 20 5
A saveDeferred() 5 10 3
A commit() 0 13 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 *
4
 * This file is part of phpFastCache.
5
 *
6
 * @license MIT License (MIT)
7
 *
8
 * For full copyright and license information, please see the docs/CREDITS.txt file.
9
 *
10
 * @author Khoa Bui (khoaofgod)  <[email protected]> http://www.phpfastcache.com
11
 * @author Georges.L (Geolim4)  <[email protected]>
12
 *
13
 */
14
15
namespace phpFastCache\Core\Pool;
16
17
use phpFastCache\Core\Item\ExtendedCacheItemInterface;
18
use phpFastCache\CacheManager;
19
use phpFastCache\Exceptions\phpFastCacheCoreException;
20
use Psr\Cache\CacheItemInterface;
21
use phpFastCache\Util\ClassNamespaceResolverTrait;
22
23
/**
24
 * Trait StandardPsr6StructureTrait
25
 * @package phpFastCache\Core
26
 *
27
 */
28
trait CacheItemPoolTrait
29
{
30
    use ClassNamespaceResolverTrait;
31
32
    /**
33
     * @var array
34
     */
35
    protected $deferredList = [];
36
37
    /**
38
     * @var ExtendedCacheItemInterface[]
39
     */
40
    protected $itemInstances = [];
41
42
    /**
43
     * @param string $key
44
     * @return \phpFastCache\Core\Item\ExtendedCacheItemInterface
45
     * @throws \InvalidArgumentException
46
     * @throws \LogicException
47
     * @throws phpFastCacheCoreException
48
     */
49
    public function getItem($key)
50
    {
51
        if (is_string($key)) {
52
            if (!array_key_exists($key, $this->itemInstances)) {
53
54
                /**
55
                 * @var $item ExtendedCacheItemInterface
56
                 */
57
                CacheManager::$ReadHits++;
58
                $class = new \ReflectionClass((new \ReflectionObject($this))->getNamespaceName() . '\Item');
59
                $item = $class->newInstanceArgs([$this, $key]);
60
                $driverArray = $this->driverRead($item);
61
62
                if ($driverArray) {
63
                    if(!is_array($driverArray)){
64
                        throw new phpFastCacheCoreException(sprintf('The driverRead method returned an unexpected variable type: %s', gettype($driverArray)));
65
                    }
66
                    $item->set($this->driverUnwrapData($driverArray));
67
                    $item->expiresAt($this->driverUnwrapEdate($driverArray));
68
69
                    if($this->config['itemDetailedDate']){
0 ignored issues
show
Bug introduced by
The property config does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
70
71
                        /**
72
                         * If the itemDetailedDate has been
73
                         * set after caching, we MUST inject
74
                         * a new DateTime object on the fly
75
                         */
76
                        $item->setCreationDate($this->driverUnwrapCdate($driverArray) ?: new \DateTime());
77
                        $item->setModificationDate($this->driverUnwrapMdate($driverArray) ?: new \DateTime());
78
                    }
79
80
                    $item->setTags($this->driverUnwrapTags($driverArray));
81
                    if ($item->isExpired()) {
82
                        /**
83
                         * Using driverDelete() instead of delete()
84
                         * to avoid infinite loop caused by
85
                         * getItem() call in delete() method
86
                         * As we MUST return an item in any
87
                         * way, we do not de-register here
88
                         */
89
                        $this->driverDelete($item);
90
                    } else {
91
                        $item->setHit(true);
92
                    }
93
                }else{
94
                    $item->expiresAfter(abs((int) $this->getConfig()[ 'defaultTtl' ]));
95
                }
96
97
            }
98
        } else {
99
            throw new \InvalidArgumentException(sprintf('$key must be a string, got type "%s" instead.', gettype($key)));
100
        }
101
102
        return $this->itemInstances[ $key ];
103
    }
104
105
    /**
106
     * @param \Psr\Cache\CacheItemInterface $item
107
     * @return $this
108
     * @throws \InvalidArgumentException
109
     */
110
    public function setItem(CacheItemInterface $item)
111
    {
112
        if ($this->getClassNamespace() . '\\Item' === get_class($item)) {
113
            $this->itemInstances[ $item->getKey() ] = $item;
114
115
            return $this;
116
        } else {
117
            throw new \InvalidArgumentException(sprintf('Invalid Item Class "%s" for this driver.', get_class($item)));
118
        }
119
    }
120
121
    /**
122
     * @param array $keys
123
     * @return CacheItemInterface[]
124
     * @throws \InvalidArgumentException
125
     */
126
    public function getItems(array $keys = [])
127
    {
128
        $collection = [];
129
        foreach ($keys as $key) {
130
            $collection[ $key ] = $this->getItem($key);
131
        }
132
133
        return $collection;
134
    }
135
136
    /**
137
     * @param string $key
138
     * @return bool
139
     * @throws \InvalidArgumentException
140
     */
141
    public function hasItem($key)
142
    {
143
        CacheManager::$ReadHits++;
144
145
        return $this->getItem($key)->isHit();
146
    }
147
148
    /**
149
     * @return bool
150
     */
151
    public function clear()
152
    {
153
        CacheManager::$WriteHits++;
154
        $this->itemInstances = [];
155
156
        return $this->driverClear();
157
    }
158
159
    /**
160
     * @param string $key
161
     * @return bool
162
     * @throws \InvalidArgumentException
163
     */
164
    public function deleteItem($key)
165
    {
166
        $item = $this->getItem($key);
167
        if ($this->hasItem($key) && $this->driverDelete($item)) {
168
            $item->setHit(false);
169
            CacheManager::$WriteHits++;
170
            /**
171
             * De-register the item instance
172
             * then collect gc cycles
173
             */
174
            $this->deregisterItem($key);
175
176
            return true;
177
        }
178
179
        return false;
180
    }
181
182
    /**
183
     * @param array $keys
184
     * @return bool
185
     * @throws \InvalidArgumentException
186
     */
187
    public function deleteItems(array $keys)
188
    {
189
        $return = null;
190
        foreach ($keys as $key) {
191
            $result = $this->deleteItem($key);
192
            if ($result !== false) {
193
                $return = $result;
194
            }
195
        }
196
197
        return (bool) $return;
198
    }
199
200
    /**
201
     * @param \Psr\Cache\CacheItemInterface $item
202
     * @return mixed
203
     * @throws \InvalidArgumentException
204
     * @throws \RuntimeException
205
     */
206
    public function save(CacheItemInterface $item)
207
    {
208
        /**
209
         * @var ExtendedCacheItemInterface $item
210
         */
211 View Code Duplication
        if (!array_key_exists($item->getKey(), $this->itemInstances)) {
1 ignored issue
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...
212
            $this->itemInstances[ $item->getKey() ] = $item;
213
        } else if(spl_object_hash($item) !== spl_object_hash($this->itemInstances[ $item->getKey() ])){
214
            throw new \RuntimeException('Spl object hash mismatches ! You probably tried to save a detached item which has been already retrieved from cache.');
215
        }
216
217
        if ($this->driverWrite($item) && $this->driverWriteTags($item)) {
218
            $item->setHit(true);
219
            CacheManager::$WriteHits++;
220
221
            return true;
222
        }
223
224
        return false;
225
    }
226
227
228
    /**
229
     * @param \Psr\Cache\CacheItemInterface $item
230
     * @return \Psr\Cache\CacheItemInterface
231
     * @throws \RuntimeException
232
     */
233
    public function saveDeferred(CacheItemInterface $item)
234
    {
235 View Code Duplication
        if (!array_key_exists($item->getKey(), $this->itemInstances)) {
1 ignored issue
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...
236
            $this->itemInstances[ $item->getKey() ] = $item;
237
        }else if(spl_object_hash($item) !== spl_object_hash($this->itemInstances[ $item->getKey() ])){
238
            throw new \RuntimeException('Spl object hash mismatches ! You probably tried to save a detached item which has been already retrieved from cache.');
239
        }
240
241
        return $this->deferredList[ $item->getKey() ] = $item;
242
    }
243
244
    /**
245
     * @return mixed|null
246
     * @throws \InvalidArgumentException
247
     */
248
    public function commit()
249
    {
250
        $return = null;
251
        foreach ($this->deferredList as $key => $item) {
252
            $result = $this->save($item);
253
            if ($return !== false) {
254
                unset($this->deferredList[ $key ]);
255
                $return = $result;
256
            }
257
        }
258
259
        return (bool) $return;
260
    }
261
}