Completed
Push — master ( 6e42b9...42c1ef )
by Kevin
02:20
created

Psr6CacheStorage::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
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
    public function __construct(CacheItemPoolInterface $cachePool)
32
    {
33
        $this->cachePool = $cachePool;
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function fetch($key)
40
    {
41
        $item = $this->cachePool->getItem($key);
42
        $this->lastItem = $item;
43
44
        $cache = $item->get();
45
46
        if ($cache instanceof CacheEntry) {
47
            return $cache;
48
        }
49
50
        return null;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function save($key, CacheEntry $data)
57
    {
58
        if ($this->lastItem && $this->lastItem->getKey() == $key) {
59
            $item = $this->lastItem;
60
        } else {
61
            $item = $this->cachePool->getItem($key);
62
        }
63
64
        $this->lastItem = null;
65
66
        $item->set($data);
67
68
        $ttl = $data->getTTL();
69
        if ($ttl === 0) {
70
            // No expiration
71
            $item->expiresAfter(null);
72
        } else {
73
            $item->expiresAfter($ttl);
74
        }
75
76
        return $this->cachePool->save($item);
77
    }
78
}
79