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