Completed
Push — master ( 28aaac...520645 )
by Antoine
03:49
created

Redis::cache()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 11
ccs 9
cts 9
cp 1
rs 9.4285
cc 2
eloc 6
nc 2
nop 1
crap 2
1
<?php
2
3
/**
4
 * This file is part of the Geotools library.
5
 *
6
 * (c) Antoine Corcy <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace League\Geotools\Cache;
13
14
use League\Geotools\Batch\BatchGeocoded;
15
use Predis\Client;
16
17
/**
18
 * Redis cache class.
19
 *
20
 * @author Antoine Corcy <[email protected]>
21
 */
22
class Redis extends AbstractCache implements CacheInterface
23
{
24
    /**
25
     * The redis cache.
26
     *
27
     * @var \Predis\Client
28
     */
29
    protected $redis;
30
31
    /**
32
     * The expire value for keys.
33
     *
34
     * @var integer
35
     */
36
    protected $expire;
37
38
39
    /**
40
     * Constructor.
41
     *
42
     * @param array   $client The client information (optional).
43
     * @param integer $expire The expire value in seconds (optional).
44
     */
45 6
    public function __construct(array $client = array(), $expire = 0)
46
    {
47 6
        $this->redis  = new Client($client);
48 6
        $this->expire = (int) $expire;
49 6
    }
50
51
    /**
52
     * {@inheritDoc}
53
     */
54 6
    public function getKey($providerName, $query)
55
    {
56 4
        return md5($providerName . $query);
57 6
    }
58
59
    /**
60
     * {@inheritDoc}
61
     */
62 1
    public function cache(BatchGeocoded $geocoded)
63
    {
64 1
        $this->redis->set(
65 1
            $key = $this->getKey($geocoded->getProviderName(), $geocoded->getQuery()),
66 1
            $this->serialize($geocoded)
67 1
        );
68
69 1
        if ($this->expire > 0) {
70 1
            $this->redis->expire($key, $this->expire);
71 1
        }
72 1
    }
73
74
    /**
75
     * {@inheritDoc}
76
     */
77 2
    public function isCached($providerName, $query)
78
    {
79 2
        if (!$this->redis->exists($key = $this->getKey($providerName, $query))) {
80 1
            return false;
81
        }
82
83 1
        $cached = new BatchGeocoded;
84 1
        $cached->fromArray($this->deserialize($this->redis->get($key)));
85
86 1
        return $cached;
87
    }
88
89
    /**
90
     * {@inheritDoc}
91
     */
92 1
    public function flush()
93
    {
94 1
        $this->redis->flushDb();
95 1
    }
96
}
97