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