Skip to content

Commit

Permalink
Decoding empty body resulted in syntax error
Browse files Browse the repository at this point in the history
  • Loading branch information
jms-pantheon committed Jan 31, 2025
1 parent d53ff89 commit 902287a
Showing 1 changed file with 23 additions and 11 deletions.
34 changes: 23 additions & 11 deletions src/Request/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -421,21 +421,33 @@ public function request($path, array $options = []): RequestOperationResult
$options
);
$body = $response->getBody()->getContents();
try {
$body = \json_decode(
$body,
false,
512,
JSON_THROW_ON_ERROR
);
} catch (\JsonException $jsonException) {
$this->logger->debug($jsonException->getMessage());
$statusCode = $response->getStatusCode();
$headers = $response->getHeaders();

// Don't attempt to decode JSON if the response is expected to have no body.
if (
!in_array($statusCode, [204, 304], true)
&& (!isset($headers['Content-Length']) || $headers['Content-Length'][0] != '0')
&& !empty($body)) {
try {
$body = \json_decode(
$body,
false,
512,
JSON_THROW_ON_ERROR
);
} catch (\JsonException $jsonException) {
$this->logger->debug($jsonException->getMessage());
$body = null;
}
} else {
$body = null;
}

return new RequestOperationResult([
'data' => $body,
'headers' => $response->getHeaders(),
'status_code' => $response->getStatusCode(),
'headers' => $headers,
'status_code' => $statusCode,
'status_code_reason' => $response->getReasonPhrase(),
]);
}
Expand Down

0 comments on commit 902287a

Please sign in to comment.