remove redundant cache prefix
[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, &$val = null, &$ltl = null, $update = false) {
27 if (!$item = $this->rd->get($this->key($key))) {
28 header("Cache-Item: ".serialize($item), false);
29 return false;
30 }
31
32 $val = $item->value;
33 $ttl = $item->ttl;
34 $set = $item->time;
35
36 if (!isset($ttl)) {
37 return true;
38 }
39 $now = time();
40 $ltl = $ttl - ($now - $set);
41 if ($ltl >= 0) {
42 if ($update) {
43 $item->time = time();
44 $this->rd->setex($this->key($key), $ttl + 60*60*24, $item);
45 }
46 return true;
47 }
48 return false;
49 }
50
51 function set($key, $val, $ttl = null) {
52 $item = new Redis\Item([
53 "value" => $val,
54 "ttl" => $ttl,
55 "time" => isset($ttl) ? time() : null
56 ]);
57 if (isset($ttl)) {
58 $this->rd->set($this->key($key), $item);
59 } else {
60 $this->rd->setex($this->key($key), $ttl + 60*60*24, $item);
61 }
62 return $this;
63 }
64
65 function del($key) {
66 $this->rd->delete($this->key($key));
67 }
68 }
69
70 namespace app\Github\Storage\Redis;
71
72 class Item
73 {
74 public $value;
75 public $time;
76 public $ttl;
77
78 function __construct(array $data) {
79 foreach ($data as $key => $val) {
80 $this->$key = $val;
81 }
82 }
83 }
84