a9da6d6c731bc8ed60d8ab011e04d66feb472a19
[m6w6/seekat] / lib / Exception / RequestException.php
1 <?php
2
3 namespace seekat\Exception;
4
5 use Exception as BaseException;
6 use http\ {
7 Client\Response,
8 Header
9 };
10 use seekat\Exception;
11
12 class RequestException extends BaseException implements Exception
13 {
14 /**
15 * JSON errors
16 * @var array
17 */
18 private $errors = [];
19
20 /**
21 * The response of the request which caused the exception
22 * @var Response
23 */
24 private $response;
25
26 /**
27 * @param Response $response
28 */
29 function __construct(Response $response) {
30 $this->response = $response;
31
32 if (($h = $response->getHeader("Content-Type", Header::class))
33 && $h->match("application/json", Header::MATCH_WORD)
34 && $failure = json_decode($response->getBody())) {
35 $message = $failure->message;
36 if (isset($failure->errors)) {
37 $this->errors = (array) $failure->errors;
38 }
39 } else {
40 $message = trim($response->getBody()->toString());
41 }
42
43 if (!strlen($message)) {
44 $message = $response->getTransferInfo("error");
45 }
46 if (!strlen($message)) {
47 $message = $response->getResponseStatus();
48 }
49
50 parent::__construct($message, $response->getResponseCode(), null);
51 }
52
53 /**
54 * Get JSON errors
55 * @return array
56 */
57 function getErrors() : array {
58 return $this->errors;
59 }
60
61 /**
62 * Combine any errors into a single string
63 * @staticvar array $reasons
64 * @return string
65 */
66 function getErrorsAsString() {
67 static $reasons = [
68 "missing" => "The resource %1\$s does not exist\n",
69 "missing_field" => "Missing field %2\$s of resource %1\$s\n",
70 "invalid" => "Invalid formatting of field %2\$s of resource %1\$s\n",
71 "already_exists" => "A resource %1\$s with the same value of field %2\$s already exists\n",
72 ];
73
74 if (!$this->errors) {
75 return $this->response;
76 }
77
78 $errors = "JSON errors:\n";
79 foreach ($this->errors as $error) {
80 if ($error->code === "custom") {
81 $errors .= $error->message . "\n";
82 } else {
83 $errors .= sprintf($reasons[$error->code], $error->resource, $error->field);
84 }
85 }
86 return $errors;
87 }
88
89 /**
90 * @return string
91 */
92 function __toString() : string {
93 return parent::__toString() . "\n". $this->getErrorsAsString();
94 }
95 }