Completed
Push — master ( 100b5c...28aaac )
by Antoine
09:01 queued 05:30
created

Redis::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 2
eloc 6
c 2
b 0
f 1
nc 2
nop 2
dl 0
loc 9
ccs 5
cts 6
cp 0.8333
crap 2.0185
rs 9.6666
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\Exception\InvalidArgumentException;
15
use League\Geotools\Batch\BatchGeocoded;
16
use Predis\Client;
17
18
/**
19
 * Redis cache class.
20
 *
21
 * @author Antoine Corcy <[email protected]>
22
 */
23
class Redis extends AbstractCache implements CacheInterface
24
{
25
    /**
26
     * The redis cache.
27
     *
28
     * @var \Predis\Client
29
     */
30
    protected $redis;
31
32
    /**
33
     * The expire value for keys.
34
     *
35
     * @var integer
36
     */
37
    protected $expire;
38
39
40
    /**
41
     * Constructor.
42
     *
43
     * @param array   $client The client information (optional).
44
     * @param integer $expire The expire value in seconds (optional).
45
     *
46
     * @throws InvalidArgumentException
47
     */
48 6
    public function __construct(array $client = array(), $expire = 0)
49
    {
50
        try {
51 6
            $this->redis  = new Client($client);
52 6
            $this->expire = (int) $expire;
53 6
        } catch (\Exception $e) {
54
            throw new InvalidArgumentException($e->getMessage());
55
        }
56 6
    }
57
58
    /**
59
     * {@inheritDoc}
60
     */
61 4
    public function getKey($providerName, $query)
62
    {
63 4
        return md5($providerName . $query);
64
    }
65
66
    /**
67
     * {@inheritDoc}
68
     */
69 1
    public function cache(BatchGeocoded $geocoded)
70
    {
71 1
        $this->redis->set(
72 1
            $key = $this->getKey($geocoded->getProviderName(), $geocoded->getQuery()),
73 1
            $this->serialize($geocoded)
74 1
        );
75
76 1
        if ($this->expire > 0) {
77 1
            $this->redis->expire($key, $this->expire);
78 1
        }
79 1
    }
80
81
    /**
82
     * {@inheritDoc}
83
     */
84 2
    public function isCached($providerName, $query)
85
    {
86 2
        if (!$this->redis->exists($key = $this->getKey($providerName, $query))) {
87 1
            return false;
88
        }
89
90 1
        $cached = new BatchGeocoded;
91 1
        $cached->fromArray($this->deserialize($this->redis->get($key)));
92
93 1
        return $cached;
94
    }
95
96
    /**
97
     * {@inheritDoc}
98
     */
99 1
    public function flush()
100
    {
101 1
        $this->redis->flushDb();
102 1
    }
103
}
104