Passed
Push — master ( dbf047...1b561f )
by Daniel
02:26
created

Cache   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 6
eloc 14
c 1
b 0
f 1
dl 0
loc 55
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 9 2
A __construct() 0 3 1
A set() 0 14 3
1
<?php
2
3
namespace Jellyfish\CacheSymfony;
4
5
use Jellyfish\Cache\CacheInterface;
6
use Jellyfish\Cache\Exception\InvalidLifeTimeException;
7
use Symfony\Component\Cache\Adapter\AbstractAdapter;
8
9
class Cache implements CacheInterface
10
{
11
    /**
12
     * @var \Symfony\Component\Cache\Adapter\AbstractAdapter
13
     */
14
    protected $cacheAdapter;
15
16
    /**
17
     * @param \Symfony\Component\Cache\Adapter\AbstractAdapter $cacheAdapter
18
     */
19
    public function __construct(AbstractAdapter $cacheAdapter)
20
    {
21
        $this->cacheAdapter = $cacheAdapter;
22
    }
23
24
25
    /**
26
     * @param string $key
27
     *
28
     * @return string|null
29
     */
30
    public function get(string $key): ?string
31
    {
32
        $cacheItem = $this->cacheAdapter->getItem($key);
33
34
        if (!$cacheItem->isHit()) {
35
            return null;
36
        }
37
38
        return $cacheItem->get();
39
    }
40
41
    /**
42
     * @param string $key
43
     * @param string $value
44
     * @param int|null $lifeTime
45
     *
46
     * @return \Jellyfish\Cache\CacheInterface
47
     *
48
     * @throws \Jellyfish\Cache\Exception\InvalidLifeTimeException
49
     */
50
    public function set(string $key, string $value, ?int $lifeTime = null): CacheInterface
51
    {
52
        if ($lifeTime !== null && $lifeTime <= 0) {
53
            throw new InvalidLifeTimeException('The life time value must be greater then zero or null!');
54
        }
55
56
        $cacheItem = $this->cacheAdapter->getItem($key);
57
58
        $cacheItem->set($value)
59
            ->expiresAfter($lifeTime);
60
61
        $this->cacheAdapter->save($cacheItem);
62
63
        return $this;
64
    }
65
}
66