Passed
Push — master ( d8c2a1...59198c )
by Kevin
07:55
created

Psr6CacheStorage::delete()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 8
c 0
b 0
f 0
ccs 0
cts 5
cp 0
rs 9.4285
cc 3
eloc 4
nc 2
nop 1
crap 12
1
<?php
2
3
namespace Kevinrob\GuzzleCache\Storage;
4
5
use Psr\Cache\CacheItemInterface;
6
use Psr\Cache\CacheItemPoolInterface;
7
use Kevinrob\GuzzleCache\CacheEntry;
8
9
class Psr6CacheStorage implements CacheStorageInterface
10
{
11
    /**
12
     * The cache pool.
13
     *
14
     * @var CacheItemPoolInterface
15
     */
16
    protected $cachePool;
17
18
    /**
19
     * The last item retrieved from the cache.
20
     *
21
     * This item is transiently stored so that save() can reuse the cache item
22
     * usually retrieved by fetch() beforehand, instead of requesting it a second time.
23
     *
24
     * @var CacheItemInterface|null
25
     */
26
    protected $lastItem;
27
28
    /**
29
     * @param CacheItemPoolInterface $cachePool
30
     */
31 2
    public function __construct(CacheItemPoolInterface $cachePool)
32
    {
33 2
        $this->cachePool = $cachePool;
34 2
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39 2
    public function fetch($key)
40
    {
41 2
        $item = $this->cachePool->getItem($key);
42 2
        $this->lastItem = $item;
43
44 2
        $cache = $item->get();
45
46 2
        if ($cache instanceof CacheEntry) {
47 2
            return $cache;
48
        }
49
50
        return null;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56 2
    public function save($key, CacheEntry $data)
57
    {
58 2
        if ($this->lastItem && $this->lastItem->getKey() == $key) {
59
            $item = $this->lastItem;
60
        } else {
61 2
            $item = $this->cachePool->getItem($key);
62
        }
63
64 2
        $this->lastItem = null;
65
66 2
        $item->set($data);
67
68 2
        $ttl = $data->getTTL();
69 2
        if ($ttl === 0) {
70
            // No expiration
71
            $item->expiresAfter(null);
72
        } else {
73 2
            $item->expiresAfter($ttl);
74
        }
75
76 2
        return $this->cachePool->save($item);
77
    }
78
79
    /**
80
     * @param string $key
81
     *
82
     * @return bool
83
     */
84
    public function delete($key)
85
    {
86
        if (null !== $this->lastItem && $this->lastItem->getKey() === $key) {
87
            $this->lastItem = null;
88
        }
89
90
        return $this->cachePool->deleteItem($key);
91
    }
92
}
93