NumverifyApiFailureException::getReasonPhrase()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 2
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * This file is part of the Numverify API Client for PHP.
7
 *
8
 * (c) 2024 Eric Sizemore <[email protected]>
9
 * (c) 2018-2021 Mark Rogoyski <[email protected]>
10
 *
11
 * This source file is subject to the MIT license. For the full copyright,
12
 * license information, and credits/acknowledgements, please view the LICENSE
13
 * and README files that were distributed with this source code.
14
 */
15
16
namespace Numverify\Exception;
17
18
use Psr\Http\Message\ResponseInterface;
19
use RuntimeException;
20
use stdClass;
21
22
use function json_decode;
23
24
/**
25
 * Thrown when the Numverify API returns a failure response.
26
 *
27
 * @see \Numverify\Tests\Exception\NumverifyApiFailureExceptionTest
28
 */
29
class NumverifyApiFailureException extends RuntimeException
30
{
31
    private readonly string $body;
32
33
    private readonly string $reasonPhrase;
34
35
    private readonly int $statusCode;
36
37 15
    public function __construct(ResponseInterface $response)
38
    {
39 15
        $this->statusCode   = $response->getStatusCode();
40 15
        $this->reasonPhrase = $response->getReasonPhrase();
41 15
        $this->body         = (string) $response->getBody();
42
43 15
        $message = $this->parseMessageFromBody($this->body);
44
45 15
        parent::__construct($message);
46
    }
47
48 1
    public function getBody(): string
49
    {
50 1
        return $this->body;
51
    }
52
53 11
    public function getReasonPhrase(): string
54
    {
55 11
        return $this->reasonPhrase;
56
    }
57
58 1
    public function getStatusCode(): int
59
    {
60 1
        return $this->statusCode;
61
    }
62
63
    /**
64
     * Parse JSON body error message.
65
     *
66
     * Expecting a JSON body like:
67
     * {
68
     *     "success":false,
69
     *     "error":{
70
     *         "code":101,
71
     *         "type":"invalid_access_key",
72
     *         "info":"You have not supplied a valid API Access Key. [Technical Support: [email protected]]"
73
     *     }
74
     * }
75
     */
76 15
    private function parseMessageFromBody(string $jsonBody): string
77
    {
78
        /** @var stdClass $body */
79 15
        $body = json_decode($jsonBody);
80
81 15
        if (!isset($body->error)) {
82 11
            return \sprintf('Unknown error - %d %s', $this->statusCode, $this->getReasonPhrase());
83
        }
84
85
        /** @var object{type: string, code: int, info: string} $error */
86 4
        $error = $body->error;
87
88 4
        return \sprintf('Type:%s Code:%d Info:%s', $error->type, $error->code, $error->info);
89
    }
90
}
91