refactor guthub api
[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 (empty($this->args["fresh"]) && ($cache = $this->api->getCacheStorage())) {
61 $key = $this->getCacheKey();
62
63 if ($cache->get($key, $cached)) {
64 call_user_func_array($callback, $cached);
65 return $this->api->getClient();
66 }
67 }
68
69 $this->enqueue($callback);
70 return $this->api->getClient();
71 }
72
73 /**
74 * Get type of call
75 * @return string
76 */
77 function __toString() {
78 $parts = explode("\\", get_class($this));
79 return strtolower(end($parts));
80 }
81
82 /**
83 * Get associated cache storage
84 * @param int $ttl out param of configure ttl
85 * @return Storage
86 */
87 function getCache(&$ttl = null) {
88 if (isset($this->config->storage->cache->{$this}->ttl)) {
89 $ttl = $this->config->storage->cache->{$this}->ttl;
90 }
91 return $this->api->getCacheStorage();
92 }
93
94 function getCacheKey() {
95 return sprintf("github:%s:%s:%s", $this->api->getToken(), $this,
96 new QueryString($this->args));
97 }
98
99 function readFromCache(&$cached = null, &$ttl = null) {
100 if (empty($this->args["fresh"]) && ($cache = $this->api->getCacheStorage())) {
101 $key = $this->getCacheKey();
102 return $cache->get($key, $cached, $ttl);
103 }
104 return false;
105 }
106
107 function saveToCache($fresh) {
108 if (($cache = $this->api->getCacheStorage())) {
109 if (isset($this->config->storage->cache->{$this}->ttl)) {
110 $ttl = $this->config->storage->cache->{$this}->ttl;
111 } else {
112 $ttl = 0;
113 }
114
115 $key = $this->getCacheKey();
116 $cache->set($key, $fresh, $ttl);
117 }
118 }
119 }