refactor guthub api
[pharext/pharext.org] / app / Github / Exception / RequestException.php
1 <?php
2
3 namespace app\Github\Exception;
4
5 use app\Github\Exception;
6 use http\Header;
7 use http\Client\Response;
8
9 class RequestException extends \Exception implements Exception
10 {
11 protected $errors = [];
12
13 function __construct(Response $response) {
14 if (($h = $response->getHeader("Content-Type", Header::class))
15 && $h->match("application/json", Header::MATCH_WORD)
16 && $failure = json_decode($response->getBody())) {
17 $message = $failure->message;
18 if (isset($failure->errors)) {
19 $this->errors = (array) $failure->errors;
20 }
21 } else {
22 $message = $response->getBody()->toString();
23 }
24
25 if (!strlen($message)) {
26 $message = $response->getTransferInfo("error");
27 }
28
29 parent::__construct($message, $response->getResponseCode(), null);
30 }
31
32 function getErrors() {
33 return $this->errors;
34 }
35
36 function getErrorsAsString() {
37 static $reasons = [
38 "missing" => "The resource %1\$s does not exist\n",
39 "missing_field" => "Missing field %2\$s of resource %1\$s\n",
40 "invalid" => "Invalid formatting of field %2\$s of resource %1\$s\n",
41 "already_exists" => "A resource %1\$s with the same value of field %2\$s already exists\n",
42 ];
43
44 if (!$this->errors) {
45 return "";
46 }
47
48 $errors = "JSON errors:\n";
49 foreach ($this->errors as $error) {
50 $errors .= sprintf($reasons[$error->code], $error->resource, $error->field);
51 }
52 return $errors;
53 }
54 function __toString() {
55 return parent::__toString() . "\n". $this->getErrorsAsString();
56 }
57 }