3 namespace app\Github\API
;
6 use app\Github\Storage\Item
;
7 use http\Client\Response
;
22 * @var \app\Gituhub\API
42 * @var \React\Promise\Deferred
49 abstract protected function request();
54 abstract protected function response(Response
$response);
60 function __construct(API
$api, array $args = null) {
62 $this->config
= $this->api
->getConfig();
63 $this->url
= new Url($this->config
->api
->url
, null, 0);
64 $this->deferred
= new Promise\Deferred
;
69 if (isset($this->config
->api
->call
->{$this}->args
)) {
70 $this->args +
= $this->config
->api
->call
->{$this}->args
->toArray();
75 * @return \React\Promise\Promise
78 if ($this->readFromCache($this->result
)) {
79 return new Promise\
FulfilledPromise($this->result
);
81 $this->api
->getClient()->enqueue(
85 $result = $this->response($response);
86 if (!($result instanceof Promise\PromiseInterface
)) {
87 $this->deferred
->resolve($result);
89 } catch (\Exception
$e) {
90 $this->deferred
->reject($e);
95 return $this->deferred
->promise();
103 function __toString() {
104 $parts = explode("\\", get_class($this));
105 return strtolower(end($parts));
109 * Get associated cache storage
110 * @param int $ttl out param of configure ttl
113 function getCache(&$ttl = null) {
114 if (isset($this->config
->storage
->cache
->{$this}->ttl
)) {
115 $ttl = $this->config
->storage
->cache
->{$this}->ttl
;
117 return $this->api
->getCacheStorage();
120 function getCacheKey() {
122 unset($args["fresh"]);
123 if (isset($args["page"]) && !strcmp($args["page"], "1")) {
124 unset($args["page"]);
127 return sprintf("%s:%s:%s", $this->api
->getToken(), $this,
128 new QueryString($args));
131 function readFromCache(array &$value = null) {
132 if (!empty($this->args
["fresh"])) {
135 if (!($cache = $this->api
->getCacheStorage())) {
138 if (!strlen($key = $this->getCacheKey())) {
141 if (!$cache->get($key, $cached)) {
143 $this->api
->getLogger()->debug(
144 sprintf("Cache-Stale: $this [TTL=%d]", $cached->getTTL()),
147 $this->api
->getLogger()->debug("Cache-Miss: $this", $this->args
);
151 if (null !== $this->api
->getMaxAge() && $cached->getAge() > $this->api
->getMaxAge()) {
152 $this->api
->getLogger()->debug("Cache-Refresh: $this", $this->args
);
155 $this->api
->getLogger()->debug("Cache-Hit: $this", $this->args
);
156 $value = $cached->getValue();
160 function saveToCache(array $fresh) {
161 if (($cache = $this->api
->getCacheStorage())) {
162 if (isset($this->config
->storage
->cache
->{$this}->ttl
)) {
163 $ttl = $this->config
->storage
->cache
->{$this}->ttl
;
168 $key = $this->getCacheKey();
169 $cache->set($key, new Item($fresh, $ttl));
170 $this->api
->getLogger()->debug("Cache-Push: $this", $this->args
);
174 function dropFromCache() {
175 if (($cache = $this->api
->getCacheStorage())) {
176 $key = $this->getCacheKey();
178 $this->api
->getLogger()->debug("Cache-Drop: $this", $this->args
);