Skip to content

Commit

Permalink
Prevent throwing JSONParseException when the response is empty. (#2125)
Browse files Browse the repository at this point in the history
  • Loading branch information
aribon-cs authored Nov 29, 2022
1 parent 35cd0dc commit b6ec347
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 20 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* Removed `CallbackStrategyTestHelper` and `ErrorsCollector` from `tests` [#2111](https://github.com/ruflin/Elastica/pull/2111)
### Fixed
* Fixed `Query/Terms` terms phpdoc from `array<bool|float|int|string>` to `list<bool|float|int|string>` [#2118](https://github.com/ruflin/Elastica/pull/2118)
* Fixed `Response` to prevent throwing JSONParseException when the response is empty.
### Security

## [7.2.0](https://github.com/ruflin/Elastica/compare/7.2.0...7.1.5)
Expand Down
47 changes: 27 additions & 20 deletions src/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -208,26 +208,7 @@ public function getStatus()
public function getData()
{
if (null == $this->_response) {
$response = $this->_responseString;

try {
if ($this->getJsonBigintConversion()) {
$response = JSON::parse($response, true, 512, \JSON_BIGINT_AS_STRING);
} else {
$response = JSON::parse($response);
}
} catch (\JsonException $e) {
// leave response as is if parse fails
}

if (empty($response)) {
$response = [];
}

if (\is_string($response)) {
$response = ['message' => $response];
}

$response = $this->getResponseString();
$this->_response = $response;
$this->_responseString = '';
}
Expand Down Expand Up @@ -357,4 +338,30 @@ public function getJsonBigintConversion()
{
return $this->_jsonBigintConversion;
}

/**
* @return array|string[]
*/
private function getResponseString()
{
$response = $this->_responseString;
if (empty($response)) {
return [];
}
try {
if ($this->getJsonBigintConversion()) {
$response = JSON::parse($response, true, 512, \JSON_BIGINT_AS_STRING);
} else {
$response = JSON::parse($response);
}
} catch (\JsonException $e) {
// leave response as is if parse fails
}

if (\is_string($response)) {
$response = ['message' => $response];
}

return $response;
}
}

0 comments on commit b6ec347

Please sign in to comment.