Lines 76.92% 20 / 26
Methods 42.85% 3 / 7
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 100.00% 8 / 8 100.00% 1 / 1 2
 fromGenerated 70.00% 7 / 10 0.00% 0 / 1 4.43
 status 100.00% 1 / 1 100.00% 1 / 1 1
 requestId 0.00% 0 / 1 0.00% 0 / 1 2
 apiMessage 100.00% 1 / 1 100.00% 1 / 1 1
 body 0.00% 0 / 1 0.00% 0 / 1 2
 parseMessage 75.00% 3 / 4 0.00% 0 / 1 4.25
17final class ApiException extends HushHushException
18{
19    private readonly int $status;
20
21    /** The parsed `error` field from hush-hush's error body, if present. */
22    private readonly ?string $apiMessage;
23
24    /** The raw, unparsed response body, for a caller that needs more than `apiMessage`. */
25    private readonly string $body;
26
27    public function __construct(int $status, string $body, private readonly ?string $requestId)
28    {
29        $apiMessage = self::parseMessage($body);
30        parent::__construct(
31            null !== $apiMessage ? "hush-hush: {$status}: {$apiMessage}" : "hush-hush: unexpected status {$status}",
32            $status,
33        );
34        $this->status = $status;
35        $this->apiMessage = $apiMessage;
36        $this->body = $body;
37    }
38
39    public static function fromGenerated(GeneratedApiException $exception): self
40    {
41        $status = $exception->getCode();
42        $body = $exception->getResponseBody();
43        $bodyString = \is_string($body) ? $body : (string) json_encode($body);
44
45        $requestId = null;
46        $headers = $exception->getResponseHeaders() ?? [];
47        foreach ($headers as $name => $values) {
48            if (0 === strcasecmp((string) $name, 'X-Request-Id')) {
49                $requestId = $values[0] ?? null;
50
51                break;
52            }
53        }
54
55        return new self($status, $bodyString, $requestId);
56    }
57
58    public function status(): int
59    {
60        return $this->status;
61    }
62
63    public function requestId(): ?string
64    {
65        return $this->requestId;
66    }
67
68    public function apiMessage(): ?string
69    {
70        return $this->apiMessage;
71    }
72
73    public function body(): string
74    {
75        return $this->body;
76    }
77
78    private static function parseMessage(string $body): ?string
79    {
80        $decoded = json_decode($body, true);
81        if (\is_array($decoded) && isset($decoded['error']) && \is_string($decoded['error'])) {
82            return $decoded['error'];
83        }
84
85        return null;
86    }
87}