Memcached::set()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 2
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
namespace Netgen\Bundle\OpenWeatherMapBundle\Cache;
4
5
use Memcached as MemcachedStore;
6
use Netgen\Bundle\OpenWeatherMapBundle\Exception\ItemNotFoundException;
7
8
class Memcached implements HandlerInterface
9
{
10
    /**
11
     * @var \Memcached
12
     */
13
    protected $memcached;
14
15
    /**
16
     * @var int
17
     */
18
    protected $ttl;
19
20
    /**
21
     * Memcached constructor.
22
     *
23
     * @param \Memcache|MemcachedStore $memcached
24
     * @param int $ttl
25
     */
26
    public function __construct(\Memcached $memcached, $ttl)
27
    {
28
        $this->memcached = $memcached;
29
        $this->memcached->setOption(MemcachedStore::OPT_PREFIX_KEY, self::CACHE_KEY_PREFIX);
30
        $this->memcached->setOption(MemcachedStore::OPT_LIBKETAMA_COMPATIBLE, true);
31
        $this->ttl = $ttl;
32
    }
33
34
    /**
35
     * {@inheritdoc}
36
     */
37
    public function has($cacheKey)
38
    {
39
        return $this->memcached->get($cacheKey) !== false;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function get($cacheKey)
46
    {
47
        $data = $this->memcached->get($cacheKey);
48
49
        if (!empty($data)) {
50
            return $data;
51
        }
52
53
        throw new ItemNotFoundException("Item with key:{$cacheKey} not found.");
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function set($cacheKey, $data)
60
    {
61
        // Memcached considers TTL smaller than 60 * 60 * 24 * 30 (number of seconds in a month)
62
        // as a relative value, so we will make sure that it is converted to a timestamp for consistent
63
        // usage later on
64
        if ($this->ttl < 60 * 60 * 24 * 30) {
65
            $this->ttl = time() + (int) $this->ttl;
66
        }
67
68
        $this->memcached->set($cacheKey, $data, $this->ttl);
69
    }
70
}
71