3 namespace app\Github\API
;
6 use app\Github\Storage\Item
;
7 use http\Client\Response
;
22 * @var \app\Gituhub\API
47 * @var \React\Promise\Deferred
54 abstract protected function request();
59 abstract protected function response(Response
$response);
65 function __construct(API
$api, array $args = null) {
67 $this->config
= $this->api
->getConfig();
68 $this->url
= new Url($this->config
->api
->url
, null, 0);
69 $this->deferred
= new Promise\Deferred
;
74 if (isset($this->config
->api
->call
->{$this}->args
)) {
75 $this->args +
= $this->config
->api
->call
->{$this}->args
->toArray();
80 * @return \React\Promise\Promise
83 if ($this->readFromCache($this->result
)) {
84 return new Promise\
FulfilledPromise($this->result
);
86 $this->api
->getClient()->enqueue(
90 $this->deferred
->resolve($this->response($response));
91 } catch (\Exception
$e) {
92 $this->deferred
->reject($e);
97 return $this->deferred
->promise();
105 function __toString() {
106 $parts = explode("\\", get_class($this));
107 return strtolower(end($parts));
111 * Call Client::send()
114 $this->api
->getClient()->send();
115 return $this->result
;
119 * Get associated cache storage
120 * @param int $ttl out param of configure ttl
123 function getCache(&$ttl = null) {
124 if (isset($this->config
->storage
->cache
->{$this}->ttl
)) {
125 $ttl = $this->config
->storage
->cache
->{$this}->ttl
;
127 return $this->api
->getCacheStorage();
130 function getCacheKey() {
132 unset($args["fresh"]);
133 if (isset($args["page"]) && !strcmp($args["page"], "1")) {
134 unset($args["page"]);
137 return sprintf("%s:%s:%s", $this->api
->getToken(), $this,
138 new QueryString($args));
141 function readFromCache(array &$value = null) {
142 if (!empty($this->args
["fresh"])) {
145 if (!($cache = $this->api
->getCacheStorage())) {
148 if (!strlen($key = $this->getCacheKey())) {
151 if (!$cache->get($key, $cached)) {
154 if (null !== $this->api
->getMaxAge() && $cached->getAge() > $this->api
->getMaxAge()) {
157 $this->api
->getLogger()->debug("Cache-Hit: $this", $this->args
);
158 $value = $cached->getValue();
162 function saveToCache(array $fresh) {
163 if (($cache = $this->api
->getCacheStorage())) {
164 if (isset($this->config
->storage
->cache
->{$this}->ttl
)) {
165 $ttl = $this->config
->storage
->cache
->{$this}->ttl
;
170 $key = $this->getCacheKey();
171 $cache->set($key, new Item($fresh, $ttl));
175 function dropFromCache() {
176 if (($cache = $this->api
->getCacheStorage())) {
177 $key = $this->getCacheKey();