Repository navigation
Expand file tree
/
Copy pathStreamResponse.php
More file actions
128 lines (113 loc) · 2.76 KB
/
Copy pathStreamResponse.php
File metadata and controls
128 lines (113 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<?php
declare(strict_types=1);
namespace GetStream;
/**
* Represents a response from the GetStream API.
*
* @template T
*/
class StreamResponse
{
/** @var T */
public mixed $data;
private int $statusCode;
private array $headers;
private ?string $rawBody;
/**
* Create a new StreamResponse.
*
* @param int $statusCode HTTP status code
* @param array $headers Response headers
* @param mixed $data Parsed response data
* @param string|null $rawBody Raw response body
*/
public function __construct(int $statusCode, array $headers, mixed $data, ?string $rawBody = null)
{
$this->statusCode = $statusCode;
$this->headers = $headers;
$this->data = $data;
$this->rawBody = $rawBody;
}
/**
* @template U
*
* @param StreamResponse<mixed> $res
* @param class-string<U> $dataClass
*
* @return StreamResponse<U>
*/
public static function fromJson(self $res, string $dataClass): self
{
$responseData = $res->getData();
// If getData() returns an array, use it directly
// If it returns a string, parse it as JSON
if (is_string($responseData)) {
$arr = json_decode($responseData, true);
} else {
$arr = $responseData;
}
// Build data object from the response data
$data = $dataClass::fromJson($arr);
return new self(
$res->getStatusCode(),
$res->getHeaders(),
$data,
$res->getRawBody()
);
}
/**
* Get the HTTP status code.
*/
public function getStatusCode(): int
{
return $this->statusCode;
}
/**
* Get the response headers.
*/
public function getHeaders(): array
{
return $this->headers;
}
/**
* Get a specific header value.
*/
public function getHeader(string $name): ?string
{
return $this->headers[strtolower($name)] ?? null;
}
/**
* Get the parsed response data.
*
* @return T
*/
public function getData(): mixed
{
return $this->data;
}
/**
* Get the raw response body.
*/
public function getRawBody(): ?string
{
return $this->rawBody;
}
/**
* Check if the response was successful (2xx status code).
*/
public function isSuccessful(): bool
{
return $this->statusCode >= 200 && $this->statusCode < 300;
}
/**
* Get the response as an array.
*/
public function toArray(): array
{
return [
'status_code' => $this->statusCode,
'headers' => $this->headers,
'data' => $this->data,
];
}
}