add redis cache storage
[pharext/pharext.org] / app / Github / API / Call.php
1 <?php
2
3 namespace app\Github\API;
4
5 use app\Github\API;
6 use http\QueryString;
7 use http\Url;
8 use merry\Config;
9
10 abstract class Call
11 {
12 /**
13 * @var Config
14 */
15 protected $config;
16
17 /**
18 * @var \app\Gituhub\API
19 */
20 protected $api;
21
22 /**
23 * @var array
24 */
25 protected $args = [];
26
27 /**
28 * @var \http\Url
29 */
30 protected $url;
31
32 /**
33 * @var QueryString
34 */
35 protected $query;
36
37 /**
38 * Queue this call to the API client
39 */
40 abstract function enqueue(callable $callback);
41
42 /**
43 * @param API $api
44 * @param array $args
45 */
46 function __construct(API $api, array $args = null) {
47 $this->api = $api;
48 $this->config = $this->api->getConfig();
49 $this->url = new Url($this->config->api->url, null, 0);
50
51 if ($args) {
52 $this->args = $args;
53 }
54 if (isset($this->config->api->call->{$this}->args)) {
55 $this->args += $this->config->api->call->{$this}->args->toArray();
56 }
57 }
58
59 function __invoke(callable $callback) {
60 if ($this->readFromCache($cached)) {
61 header("X-Cache-Hit: $this", false);
62 call_user_func_array($callback, $cached);
63 } else {
64 header("X-Cache-Miss: $this", false);
65 $this->enqueue($callback);
66 }
67 return $this;
68 }
69
70 /**
71 * Get type of call
72 * @return string
73 */
74 function __toString() {
75 $parts = explode("\\", get_class($this));
76 return strtolower(end($parts));
77 }
78
79 /**
80 * Call Client::send()
81 */
82 function send() {
83 return $this->api->getClient()->send();
84 }
85
86 /**
87 * Get associated cache storage
88 * @param int $ttl out param of configure ttl
89 * @return Storage
90 */
91 function getCache(&$ttl = null) {
92 if (isset($this->config->storage->cache->{$this}->ttl)) {
93 $ttl = $this->config->storage->cache->{$this}->ttl;
94 }
95 return $this->api->getCacheStorage();
96 }
97
98 function getCacheKey() {
99 $args = $this->args;
100 unset($args["fresh"]);
101 ksort($args);
102 return sprintf("github:%s:%s:%s", $this->api->getToken(), $this,
103 new QueryString($args));
104 }
105
106 function readFromCache(array &$cached = null, &$ttl = null) {
107 if (empty($this->args["fresh"]) && ($cache = $this->api->getCacheStorage())) {
108 $key = $this->getCacheKey();
109 return $cache->get($key, $cached, $ttl);
110 }
111 return false;
112 }
113
114 function saveToCache(array $fresh) {
115 if (($cache = $this->api->getCacheStorage())) {
116 if (isset($this->config->storage->cache->{$this}->ttl)) {
117 $ttl = $this->config->storage->cache->{$this}->ttl;
118 } else {
119 $ttl = null;
120 }
121
122 $key = $this->getCacheKey();
123 $cache->set($key, $fresh, $ttl);
124 }
125 }
126
127 function dropFromCache() {
128 if (($cache = $this->api->getCacheStorage())) {
129 $key = $this->getCacheKey();
130 $cache->del($key);
131 }
132 }
133 }