Files
hdk-core/src/Service/HttpRequestService.php
2023-03-14 18:29:05 +08:00

123 lines
3.4 KiB
PHP

<?php
declare(strict_types=1);
namespace Singularity\HDK\Core\Service;
use Ergebnis\Http\Method;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Utils;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\Utils\Codec\Json;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* 发起 Http 请求的类
*/
class HttpRequestService
{
public const TIMEOUT = 20;
/**
* @Inject()
* @var ClientFactory
*/
private ClientFactory $client;
/**
* @var array<literal-string, mixed>
*/
private array $options = [];
/**
* @param string $url
* @param array<string, string|int> $params
* @return ResponseInterface
* @throws GuzzleException
*/
public function requestGet(string $url, array $params = []): ResponseInterface
{
$request = new Request(Method\Rfc\Rfc7231::GET, $url);
return $this->getClient()->send($request, [
'params' => $params,
]);
}
private function getClient(): Client
{
return $this->client->create($this->options);
}
/**
* @param string $url
* @param array<string, mixed> $data
* @param array<string, string|int> $params
* @return ResponseInterface
* @throws GuzzleException
*/
public function requestPost(string $url, array $data = [], array $params = []): ResponseInterface
{
$data = Json::encode($data);
$request = new Request('post', $url, ['Content-Type' => 'application/json'], Utils::streamFor($data));
return $this->getClient()->send($request, [
'params' => $params,
]);
}
/**
* @param string $url
* @param array<string, mixed> $data
* @param array<string, string|int> $params
* @return ResponseInterface
* @throws GuzzleException
*/
public function requestPut(string $url, array $data = [], array $params = []): ResponseInterface
{
$data = Json::encode($data);
$request = new Request('put', $url, ['Content-Type' => 'application/json'], Utils::streamFor($data));
$result = $this->getClient()->send($request, [
'params' => $params,
]);
$json = Json::decode($result->getBody()->getContents());
if ($json['code'] !== 200) {
throw new ServerException($json['message'], $request, $result);
}
return $result;
}
/**
* 定制 options
* @param array<string, mixed> $options
* @return $this
*/
public function setOptions(array $options): HttpRequestService
{
$this->options = array_replace_recursive($this->options, $options);
return $this;
}
/**
* @param ResponseInterface $response
* @param RequestInterface $request
* @return ResponseInterface
*/
private function parseResponse(
ResponseInterface $response,
RequestInterface $request
): ResponseInterface {
if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) {
return $response;
} else {
throw new BadResponseException($response->getReasonPhrase(), $request, $response);
}
}
}