-
-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathRecordedResponse.php
More file actions
116 lines (102 loc) · 2.79 KB
/
RecordedResponse.php
File metadata and controls
116 lines (102 loc) · 2.79 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
<?php
declare(strict_types=1);
namespace Saloon\Data;
use JsonSerializable;
use Saloon\Http\Response;
use Saloon\Http\Faking\MockResponse;
class RecordedResponse implements JsonSerializable
{
/**
* Constructor
*
* @param array<string, mixed> $headers
* @param array<string, mixed> $context
*/
public function __construct(
public int $statusCode,
public array $headers = [],
public mixed $data = null,
public array $context = []
) {
//
}
/**
* Create an instance from file contents
*
* @throws \JsonException
*/
public static function fromFile(string $contents): static
{
/**
* @param array{
* statusCode: int,
* headers: array<string, mixed>,
* data: mixed,
* context: array<string, mixed>,
* } $fileData
*/
$fileData = json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
$data = $fileData['data'];
if (isset($fileData['encoding']) && $fileData['encoding'] === 'base64') {
$data = base64_decode($data);
}
return new static(
statusCode: $fileData['statusCode'],
headers: $fileData['headers'],
data: $data,
context: $fileData['context'] ?? [],
);
}
/**
* Create an instance from a Response
*
* @param Response<mixed> $response
*/
public static function fromResponse(Response $response): static
{
return new static(
statusCode: $response->status(),
headers: $response->headers()->all(),
data: $response->body(),
);
}
/**
* Encode the instance to be stored as a file
*
* @throws \JsonException
*/
public function toFile(): string
{
return json_encode($this, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
}
/**
* Create a mock response from the fixture
*/
public function toMockResponse(): MockResponse
{
return new MockResponse($this->data, $this->statusCode, $this->headers);
}
/**
* Define the JSON object if this class is converted into JSON
*
* @return array{
* statusCode: int,
* headers: array<string, mixed>,
* data: mixed,
* }
*/
public function jsonSerialize(): array
{
$response = [
'statusCode' => $this->statusCode,
'headers' => $this->headers,
'data' => $this->data,
'context' => $this->context,
];
if (mb_check_encoding($response['data'], 'UTF-8') === false) {
$response['data'] = base64_encode($response['data']);
$response['encoding'] = 'base64';
}
return $response;
}
}