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