Skip to content

Commit

Permalink
feat(Http): 增加 toRet 方法,用于将请求结果转换为 Ret 对象
Browse files Browse the repository at this point in the history
  • Loading branch information
twinh committed Apr 30, 2023
1 parent 4d140a1 commit 70aa7fa
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/Http.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
*
* @author Twin Huang <twinhuang@qq.com>
* @SuppressWarnings(PHPMD.ShortVariable)
* @mixin \RetMixin
*/
class Http extends Base implements \ArrayAccess, \Countable, \IteratorAggregate
{
Expand Down Expand Up @@ -744,6 +745,24 @@ public function getCurlInfo($option = null)
return $option ? curl_getinfo($this->ch, $option) : curl_getinfo($this->ch);
}

/**
* Convert the HTTP response to a Ret object
*
* @param array $data
* @return Ret
*/
public function toRet(array $data = [])
{
if ($this->isSuccess()) {
$response = $this->getResponse();
$extra = is_array($response) ? $response : ['data' => $response];
return $this->ret->suc($data + $extra);
}

$e = $this->getErrorException();
return $this->ret->err($data + ['code' => $e->getCode(), 'message' => $e->getMessage()]);
}

/**
* Create a new HTTP object and execute
*
Expand Down
29 changes: 29 additions & 0 deletions tests/unit/HttpTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1015,4 +1015,33 @@ public function testGetValueWhenResponseIsNotArray()

$this->assertNull($http['test']);
}

public function testToRet()
{
$http = $this->http->request([
'url' => 'https://httpbin.org/get?a=b',
'ip' => false,
'dataType' => 'json',
]);
$ret = $http->toRet(['c' => 'd']);

$this->assertRetSuc($ret);

$this->assertSame('b', $ret['args']['a']);
$this->assertSame('d', $ret['c']);
}

public function testToRetError()
{
$http = $this->http->request([
'url' => 'https://httpbin.org/status/404',
'ip' => false,
'header' => true,
'throwException' => false,
]);
$ret = $http->toRet(['c' => 'd']);

$this->assertRetErr($ret);
$this->assertSame('d', $ret['c']);
}
}

0 comments on commit 70aa7fa

Please sign in to comment.