Passed
Push — master ( 7a6467...3a1bb0 )
by Kevin
03:03
created

LaravelCacheStorage::getLifeTime()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 5
cp 0
rs 9.9332
c 0
b 0
f 0
cc 3
nc 2
nop 1
crap 12
1
<?php
2
3
namespace Kevinrob\GuzzleCache\Storage;
4
5
use Illuminate\Contracts\Cache\Repository as Cache;
6
use Kevinrob\GuzzleCache\CacheEntry;
7
8
class LaravelCacheStorage implements CacheStorageInterface
9
{
10
    /**
11
     * @var Cache
12
     */
13
    protected $cache;
14
15
    /**
16
     * @param Cache $cache
17
     */
18
    public function __construct(Cache $cache)
19
    {
20
        $this->cache = $cache;
21
    }
22
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public function fetch($key)
27
    {
28
        try {
29
            $cache = unserialize($this->cache->get($key));
30
            if ($cache instanceof CacheEntry) {
31
                return $cache;
32
            }
33
        } catch (\Exception $ignored) {
34
            return;
35
        }
36
37
        return;
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function save($key, CacheEntry $data)
44
    {
45
        try {
46
            $lifeTime = $this->getLifeTime($data);
47
            if ($lifeTime === 0) {
48
                return $this->cache->forever(
49
                    $key,
50
                    serialize($data)
51
                );
52
            } else if ($lifeTime > 0) {
53
                return $this->cache->add(
54
                    $key,
55
                    serialize($data),
56
                    $lifeTime
57
                );
58
            }
59
        } catch (\Exception $ignored) {
60
            // No fail if we can't save it the storage
61
        }
62
63
        return false;
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function delete($key)
70
    {
71
        return $this->cache->forget($key);
72
    }
73
    
74
    protected function getLifeTime(CacheEntry $data)
75
    {
76
        $version = app()->version();
77
        if (preg_match('/^\d+(\.\d+)?(\.\d+)?/', $version) && version_compare($version, '5.8.0') < 0) {
78
            // getTTL returns seconds, Laravel needs minutes before v5.8
79
            return $data->getTTL() / 60;
80
        }
81
82
        return $data->getTTL();
83
    }
84
}
85