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 $this->deferred
->resolve($this->response($response));
86 } catch (\Exception
$e) {
87 $this->deferred
->reject($e);
92 return $this->deferred
->promise();
100 function __toString() {
101 $parts = explode("\\", get_class($this));
102 return strtolower(end($parts));
106 * Get associated cache storage
107 * @param int $ttl out param of configure ttl
110 function getCache(&$ttl = null) {
111 if (isset($this->config
->storage
->cache
->{$this}->ttl
)) {
112 $ttl = $this->config
->storage
->cache
->{$this}->ttl
;
114 return $this->api
->getCacheStorage();
117 function getCacheKey() {
119 unset($args["fresh"]);
120 if (isset($args["page"]) && !strcmp($args["page"], "1")) {
121 unset($args["page"]);
124 return sprintf("%s:%s:%s", $this->api
->getToken(), $this,
125 new QueryString($args));
128 function readFromCache(array &$value = null) {
129 if (!empty($this->args
["fresh"])) {
132 if (!($cache = $this->api
->getCacheStorage())) {
135 if (!strlen($key = $this->getCacheKey())) {
138 if (!$cache->get($key, $cached)) {
141 if (null !== $this->api
->getMaxAge() && $cached->getAge() > $this->api
->getMaxAge()) {
144 $this->api
->getLogger()->debug("Cache-Hit: $this", $this->args
);
145 $value = $cached->getValue();
149 function saveToCache(array $fresh) {
150 if (($cache = $this->api
->getCacheStorage())) {
151 if (isset($this->config
->storage
->cache
->{$this}->ttl
)) {
152 $ttl = $this->config
->storage
->cache
->{$this}->ttl
;
157 $key = $this->getCacheKey();
158 $cache->set($key, new Item($fresh, $ttl));
162 function dropFromCache() {
163 if (($cache = $this->api
->getCacheStorage())) {
164 $key = $this->getCacheKey();