You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
2.2 KiB
86 lines
2.2 KiB
<?php
|
|
|
|
namespace Tansilu\HfPayLib\http;
|
|
|
|
use GuzzleHttp\Exception\InvalidArgumentException;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Tansilu\HfPayLib\exception\ApiException;
|
|
|
|
class Response
|
|
{
|
|
/**
|
|
* @var int 状态码
|
|
*/
|
|
private int $statusCode = 200;
|
|
private ?array $body = [];
|
|
|
|
private string $source;
|
|
|
|
/**
|
|
* @throws ApiException
|
|
*/
|
|
public static function make(ResponseInterface $response): Response
|
|
{
|
|
$self = new self();
|
|
$self->statusCode = $response->getStatusCode();
|
|
|
|
$self->source = $response->getBody()->getContents();
|
|
|
|
if(!empty($self->source)) {
|
|
$contentType = $response->getHeader('Content-Type');
|
|
if(empty($contentType)) {
|
|
throw new ApiException('反馈的消息未指明内容格式Content-Type');
|
|
}
|
|
$bodyFormat = explode(';', $contentType[0]);
|
|
switch ($bodyFormat[0]) {
|
|
case 'text/html':
|
|
case 'application/json':
|
|
try {
|
|
$deRet = json_decode($self->source, true);
|
|
if($deRet != null) {
|
|
$self->body = $deRet;
|
|
}
|
|
} catch (InvalidArgumentException $e) {
|
|
throw new ApiException('反馈的消息格式错误');
|
|
}
|
|
break;
|
|
case 'application/xml':
|
|
case 'text/plain':
|
|
default:
|
|
throw new ApiException('反馈的数据格式不支持处理' . $bodyFormat[0]);
|
|
}
|
|
}
|
|
return $self;
|
|
}
|
|
|
|
public static function tempInit(int $code, ?array $body): Response
|
|
{
|
|
$self = new self();
|
|
$self->statusCode = $code;
|
|
$self->body = $body;
|
|
return $self;
|
|
}
|
|
|
|
/**
|
|
* @return bool 是否成功
|
|
*/
|
|
public function isSuccess(): bool
|
|
{
|
|
return $this->statusCode >= 200 && $this->statusCode < 300;
|
|
}
|
|
|
|
public function getCode(): int
|
|
{
|
|
return $this->statusCode;
|
|
}
|
|
|
|
public function getBody(): array
|
|
{
|
|
return $this->body;
|
|
}
|
|
|
|
public function getSource(): string
|
|
{
|
|
return $this->source;
|
|
}
|
|
} |