Completed
Push — master ( 202c6b...44894d )
by Andy
01:25
created

Response::getHeaders()   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 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 1
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
3
namespace Palmtree\Curl;
4
5
class Response
6
{
7
    /** @var array */
8
    private $headers = [];
9
    /** @var string */
10
    private $body;
11
    /** @var int */
12
    private $statusCode;
13
14 13
    public function __construct(string $response = '', int $statusCode = 0)
15
    {
16 13
        $this->parse($response);
17 13
        $this->statusCode = $statusCode;
18 13
    }
19
20 1
    public function getHeaders(): array
21
    {
22 1
        return $this->headers;
23
    }
24
25 2
    public function getHeader(string $key): ?string
26
    {
27 2
        return $this->headers[$key] ?? null;
28
    }
29
30 7
    public function getBody(): string
31
    {
32 7
        return $this->body;
33
    }
34
35 1
    public function getStatusCode(): int
36
    {
37 1
        return $this->statusCode;
38
    }
39
40 1
    public function isOk(): bool
41
    {
42 1
        return $this->statusCode >= Curl::HTTP_OK_MIN && $this->statusCode <= Curl::HTTP_OK_MAX;
43
    }
44
45 1
    public function is404(): bool
46
    {
47 1
        return $this->statusCode === Curl::HTTP_NOT_FOUND;
48
    }
49
50 1
    public function __toString(): string
51
    {
52 1
        return $this->body;
53
    }
54
55 13
    private function parse(string $response)
56
    {
57 13
        $response = \explode("\r\n\r\n", $response);
58
59 13
        if (\count($response) > 1) {
60
            // We want the last two parts
61 9
            $response = \array_slice($response, -2, 2);
62
63 9
            list($headers, $body) = $response;
64
65 9
            foreach (\explode("\r\n", $headers) as $header) {
66 9
                $pair = \explode(': ', $header, 2);
67
68 9
                if (isset($pair[1])) {
69 9
                    $this->headers[$pair[0]] = $pair[1];
70
                }
71
            }
72
        } else {
73 4
            $body = $response[0];
74
        }
75
76 13
        $this->body = $body;
77 13
    }
78
}
79