c971687aa1b0e44f2e4ed811abe6d527635db935
[pharext/pharext.org] / app / Github / Storage / Redis.php
1 <?php
2
3 namespace app\Github\Storage;
4
5 use app\Github\Storage;
6
7 class Redis implements Storage
8 {
9 private $rd;
10 private $ns;
11
12 function __construct($ns = "github", \Redis $rd = null) {
13 $this->ns = $ns;
14 if (!$rd) {
15 $rd = new \Redis();
16 $rd->open("localhost");
17 $rd->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP);
18 }
19 $this->rd = $rd;
20 }
21
22 private function key($key) {
23 return sprintf("%s:%s", $this->ns, $key);
24 }
25
26 function get($key, Item &$item = null, $update = false) {
27 if (!$item = $this->rd->get($this->key($key))) {
28 return false;
29 }
30
31 if (null === $item->getTTL()) {
32 return true;
33 }
34 if ($item->getLTL() >= 0) {
35 if ($update) {
36 $item->setTimestamp();
37 $this->rd->setex($this->key($key), $item->getTTL() + 60*60*24, $item);
38 }
39 return true;
40 }
41 return false;
42 }
43
44 function set($key, Item $item) {
45 if (null === $item->getTTL()) {
46 $this->rd->set($this->key($key), $item);
47 } else {
48 $this->rd->setex($this->key($key), $item->getTTL() + 60*60*24, $item);
49 }
50 return $this;
51 }
52
53 function del($key) {
54 $this->rd->delete($this->key($key));
55 }
56 }