Skip to content

Commit

Permalink
feat(Http): 如果返回内容是 application/json,则自动解析返回内容为 JSON 数组,而不是返回纯文本
Browse files Browse the repository at this point in the history
BREAKING CHANGE: `Http` 服务如果返回内容是 `application/json`,则自动解析返回内容为 JSON 数组,而不是返回纯文本
  • Loading branch information
twinh committed Nov 2, 2023
1 parent 33dc66f commit 49adca1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
13 changes: 9 additions & 4 deletions lib/Http.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,9 @@ class Http extends Base implements \ArrayAccess, \Countable, \IteratorAggregate
* The data type could by `json`, `jsonObject`, `xml`, `query`(URL query string),
* `serialize` and `text`
*
* @var string
* @var string|null
*/
protected $dataType = 'text';
protected $dataType;

/**
* The custom HTTP referer string
Expand Down Expand Up @@ -999,10 +999,15 @@ protected function triggerError($status, \ErrorException $exception)
*/
protected function parseResponse($data, &$exception)
{
switch ($this->dataType) {
$dataType = $this->dataType;
if (!$dataType && 'application/json' === $this->getResponseHeader('CONTENT-TYPE')) {
$dataType = 'json';
}

switch ($dataType) {
case 'json':
case 'jsonObject':
$result = json_decode($data, 'json' === $this->dataType);
$result = json_decode($data, 'json' === $dataType);
if (null === $result && \JSON_ERROR_NONE != json_last_error()) {
$exception = new \ErrorException('JSON parsing error, the data is ' . $data, json_last_error());
}
Expand Down
12 changes: 12 additions & 0 deletions tests/unit/HttpTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1095,4 +1095,16 @@ public function providerForParams(): array
],
];
}

public function testDetectJson()
{
$http = $this->http->get([
'url' => 'https://httpbin.org/get',
]);
$this->assertSame('application/json', $http->getResponseHeader('CONTENT-TYPE'));

$response = $http->getResponse();
$this->assertIsArray($response);
$this->assertSame('https://httpbin.org/get', $response['url']);
}
}

0 comments on commit 49adca1

Please sign in to comment.