ResponseException::__construct()   A
last analyzed

Complexity

Conditions 4
Paths 11

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 25
rs 9.8666
cc 4
nc 11
nop 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DigitalCz\DigiSign\Exception;
6
7
use DigitalCz\DigiSign\DigiSignClient;
8
use Psr\Http\Message\ResponseInterface;
9
use Throwable;
10
11
class ResponseException extends RuntimeException
12
{
13
    /** @var ResponseInterface  */
14
    private $response;
15
16
    public function __construct(
17
        ResponseInterface $response,
18
        ?string $message = null,
19
        ?int $code = null,
20
        ?Throwable $previous = null
21
    ) {
22
        $this->response = $response;
23
        $code = $code ?? $response->getStatusCode();
24
        $message = $message ?? sprintf("%s %s", $response->getStatusCode(), $response->getReasonPhrase());
25
26
        try {
27
            $result = $this->parseResult();
28
29
            if (isset($result['title'])) {
30
                $message .= ': ' . $result['title'];
31
            }
32
33
            if (isset($result['detail'])) {
34
                $message .= ': ' . $result['detail'];
35
            }
36
        } catch (RuntimeException $e) {
37
            $message .= ': ' . $e->getMessage();
38
        }
39
40
        parent::__construct($message, $code, $previous);
41
    }
42
43
    /**
44
     * Access its underlying response object.
45
     */
46
    public function getResponse(): ResponseInterface
47
    {
48
        return $this->response;
49
    }
50
51
    /**
52
     * @return mixed[]
53
     */
54
    protected function parseResult(): array
55
    {
56
        $result = DigiSignClient::parseResponse($this->getResponse());
57
58
        if ($result === null) {
59
            throw new EmptyResultException();
60
        }
61
62
        return $result;
63
    }
64
}
65