ea9b59a70c461e7d0837e6e650c0eaf8c408e573
[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;
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 * Call Client::send()
84 */
85 function send() {
86 return $this->api->getClient()->send();
87 }
88
89 /**
90 * Get associated cache storage
91 * @param int $ttl out param of configure ttl
92 * @return Storage
93 */
94 function getCache(&$ttl = null) {
95 if (isset($this->config->storage->cache->{$this}->ttl)) {
96 $ttl = $this->config->storage->cache->{$this}->ttl;
97 }
98 return $this->api->getCacheStorage();
99 }
100
101 function getCacheKey() {
102 $args = $this->args;
103 unset($args["fresh"]);
104 ksort($args);
105 return sprintf("github:%s:%s:%s", $this->api->getToken(), $this,
106 new QueryString($args));
107 }
108
109 function readFromCache(array &$cached = null, &$ttl = null) {
110 if (empty($this->args["fresh"]) && ($cache = $this->api->getCacheStorage())) {
111 $key = $this->getCacheKey();
112 return $cache->get($key, $cached, $ttl);
113 }
114 return false;
115 }
116
117 function saveToCache(array $fresh) {
118 if (($cache = $this->api->getCacheStorage())) {
119 if (isset($this->config->storage->cache->{$this}->ttl)) {
120 $ttl = $this->config->storage->cache->{$this}->ttl;
121 } else {
122 $ttl = 0;
123 }
124
125 $key = $this->getCacheKey();
126 $cache->set($key, $fresh, $ttl);
127 }
128 }
129
130 function dropFromCache() {
131 if (($cache = $this->api->getCacheStorage())) {
132 $key = $this->getCacheKey();
133 $cache->del($key);
134 }
135 }
136 }