Skip to content

Commit 4537d83

Browse files
authored
Merge pull request #315 from gdebrauwer/empty-response-to-json
Bugfix: empty response body to json should not fail
2 parents fff7e1e + 556f738 commit 4537d83

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

src/Http/Response.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ public function getSenderException(): ?Throwable
191191
public function json(string|int|null $key = null, mixed $default = null): mixed
192192
{
193193
if (! isset($this->decodedJson)) {
194-
$this->decodedJson = json_decode($this->body(), true, 512, JSON_THROW_ON_ERROR);
194+
$this->decodedJson = json_decode($this->body() ?: '[]', true, 512, JSON_THROW_ON_ERROR);
195195
}
196196

197197
if (is_null($key)) {

tests/Unit/ResponseTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,16 @@
153153
expect($response->collect('age'))->toBeEmpty();
154154
});
155155

156+
test('the json method will return empty array if body is empty', function () {
157+
$mockClient = new MockClient([
158+
MockResponse::make('', 404),
159+
]);
160+
161+
$response = connector()->send(new UserRequest, $mockClient);
162+
163+
expect($response->json())->toBe([]);
164+
});
165+
156166
test('the toPsrResponse method will return a guzzle response', function () {
157167
$mockClient = new MockClient([
158168
MockResponse::make(['name' => 'Sam', 'work' => 'Codepotato'], 500),

0 commit comments

Comments
 (0)