Passed
Push — master ( 756e7a...85d7cc )
by Gombos
02:17
created

ApiResponse::getHttpMessage()   A

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 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Glorand\Drip\Api\Response;
4
5
use Error;
6
use Psr\Http\Message\ResponseInterface;
7
8
class ApiResponse
9
{
10
    /** @var string */
11
    protected $url;
12
    /** @var array */
13
    protected $options;
14
    /** @var ResponseInterface */
15
    protected $response;
16
    /** @var array */
17
    protected $body;
18
19 9
    public function __construct(string $url, array $options, ResponseInterface $response)
20
    {
21 9
        $this->url = $url;
22 9
        $this->options = $options;
23 9
        $this->response = $response;
24 9
        $this->body = json_decode((string) $response->getBody(), true);
25 9
    }
26
27 9
    public function getStatusCode(): int
28
    {
29 9
        return (int) $this->response->getStatusCode();
30
    }
31
32 9
    public function isSuccess(): bool
33
    {
34 9
        return $this->getStatusCode() >= 200 && $this->getStatusCode() <= 299;
35
    }
36
37 4
    public function getHttpMessage(): string
38
    {
39 4
        return $this->response->getReasonPhrase() ?? '';
40
    }
41
42 4
    public function getContents(): array
43
    {
44 4
        return $this->body;
45
    }
46
47 1
    public function getErrors()
48
    {
49 1
        if ($this->isSuccess()) {
50
            return [];
51
        }
52 1
        if (!empty($this->body['errors'])) {
53
            return array_map(function ($rec) {
54
                return new Error($rec['message'], $rec['code']);
55
            }, $this->body['errors']);
56
        } else {
57
            return [
58 1
                new Error($this->getHttpMessage(), $this->getStatusCode()),
59
            ];
60
        }
61
    }
62
}
63