12 * @var \app\Github\API
36 function __construct(API
$api, array $args = []) {
38 $this->config
= $api->getConfig();
40 $this->url
= new Url("https://api.github.com/", null, 0);
41 if (isset($this->config
->fetch
->{$this}->per_page
)) {
42 $this->url
->query
= "per_page=" . $this->config
->fetch
->{$this}->per_page
;
46 function setPage($page) {
55 function __toString() {
56 $parts = explode("\\", get_class($this));
57 return strtolower(end($parts));
60 function getStorage(&$ttl = null) {
61 if (isset($this->config
->storage
->cache
->{$this}->ttl
)) {
62 $ttl = $this->config
->storage
->cache
->{$this}->ttl
;
64 return $this->api
->getCacheStorage();
67 abstract function getRequest();
68 abstract function getException($message, $code, $previous = null);
69 abstract function getCacheKey();
71 function parseLinks(Header
$header) {
72 $params = new Params($header->value
, ",", ";", "=",
73 Params
::PARSE_RFC5988 | Params
::PARSE_ESCAPED
);
75 foreach ($params->params
as $link => $param) {
76 // strip enclosing brackets
77 $links[$param["arguments"]["rel"]] = $link;
82 function __invoke(callable
$callback) {
84 $key = $this->getCacheKey();
85 if (($cache = $this->api
->getCacheStorage())
86 && $cache->get($key, $cached, $ttl)) {
87 call_user_func_array($callback, $cached);
89 $this->enqueue($callback);
91 return $this->api
->getClient();
94 protected function wrap(callable
$callback) {
95 return function($response) use($callback) {
96 $rc = $response->getResponseCode();
99 if ($response->getHeader("Content-Type", Header
::class)->match("application/json", Header
::MATCH_WORD
)) {
100 $message = json_decode($response->getBody())->message
;
102 $message = $response->getBody();
104 throw $this->getException($message, $rc);
107 $json = json_decode($response->getBody());
108 if (($link = $response->getHeader("Link", Header
::class))) {
109 $links = $this->parseLinks($link);
114 if (isset($json->error
)) {
115 throw $this->getException($json->error_description
, $rc);
116 } elseif (($cache = $this->getStorage($ttl))) {
117 $cache->set($this->getCacheKey(), [$json, $links], $ttl);
120 $callback($json, $links);
126 function enqueue(callable
$callback) {
127 $request = $this->getRequest();
128 $wrapper = $this->wrap($callback);
129 return $this->api
->getClient()->enqueue($request, $wrapper);