webhook create&delete
[pharext/pharext.org] / app / Github / Create.php
1 <?php
2
3 namespace app\Github;
4
5 use http\Header;
6 use http\Url;
7
8 abstract class Create
9 {
10 /**
11 * @var \app\Github\API
12 */
13 protected $api;
14
15 /**
16 * @var \merry\Config
17 */
18 protected $config;
19
20 /**
21 * @var array
22 */
23 protected $args;
24
25 /**
26 * @var \http\Url
27 */
28 protected $url;
29
30 function __construct(API $api, array $args = []) {
31 $this->api = $api;
32 $this->config = $api->getConfig();
33 $this->args = $args;
34 $this->url = new Url("https://api.github.com/", null, 0);
35 }
36
37 function __toString() {
38 $parts = explode("\\", get_class($this));
39 return strtolower(end($parts));
40 }
41
42 abstract function getRequest();
43 abstract function getException($message, $code, $previous = null);
44
45 function __invoke(callable $callback) {
46 $this->enqueue($callback);
47 return $this->api->getClient();
48 }
49
50 protected function wrap(callable $callback) {
51 return function($response) use($callback) {
52 $rc = $response->getResponseCode();
53
54 if ($rc !== 201) {
55 if ($response->getHeader("Content-Type", Header::class)->match("application/json", Header::MATCH_WORD)) {
56 $message = json_decode($response->getBody())->message;
57 } else {
58 $message = $response->getBody();
59 }
60 throw $this->getException($message, $rc);
61 }
62
63 $json = json_decode($response->getBody());
64
65 if (isset($json->error)) {
66 throw $this->getException($json->error_description, $rc);
67 }
68
69 $callback($json);
70
71 return true;
72 };
73 }
74
75 function enqueue(callable $callback) {
76 $request = $this->getRequest();
77 $wrapper = $this->wrap($callback);
78 return $this->api->getClient()->enqueue($request, $wrapper);
79 }
80 }