123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <?php
- namespace app\common\Service\Pay;
- use GuzzleHttp\Client;
- use GuzzleHttp\Exception\RequestException;
- use Psr\Http\Client\ClientInterface;
- use Psr\Http\Client\ClientExceptionInterface;
- use Psr\Http\Message\RequestInterface;
- use Psr\Http\Message\ResponseInterface;
- /**
- * 本 HttpClient 主要为了解决 yansongda\pay Http 必须继承 ClientInterface 问题(fa 框架的 GuzzleHttp\client 为 6.* 未继承 psr ClientInterface
- * 也可直接将本类当作 GuzzleHttp\Client 使用
- */
- class HttpClient implements ClientInterface
- {
- /**
- * GuzzleHttp Client 实例
- * @var Client
- */
- protected $client;
- /**
- * 单例实例
- * @var HttpClient
- */
- private static $instance;
- /**
- * 构造函数
- * @param array $config
- */
- public function __construct(array $config = [])
- {
- $this->client = new Client($config);
- }
- /**
- * 获取单例实例
- * @param array $config
- * @return HttpClient
- */
- public static function instance(array $config = [])
- {
- if (!static::$instance instanceof static) {
- static::$instance = new static($config);
- }
- return static::$instance;
- }
- /**
- * 发送 PSR-7 请求并返回 PSR-7 响应
- *
- * @param RequestInterface $request
- * @return ResponseInterface
- * @throws ClientExceptionInterface 如果发生错误且无法完成请求
- */
- public function sendRequest(RequestInterface $request): ResponseInterface
- {
- try {
- return $this->client->send($request);
- } catch (RequestException $e) {
- // 将 GuzzleHttp 异常转换为 PSR 客户端异常
- throw new class($e->getMessage(), $e->getCode(), $e) extends \RuntimeException implements ClientExceptionInterface {
- // PSR ClientExceptionInterface 实现
- };
- }
- }
- /**
- * 魔术方法,将其他方法调用代理到 GuzzleHttp Client
- * 使其能够当作 GuzzleHttp\Client 使用
- *
- * @param string $method
- * @param array $arguments
- * @return mixed
- */
- public function __call($method, $arguments)
- {
- return $this->client->{$method}(...$arguments);
- }
- /**
- * 获取底层的 GuzzleHttp Client
- * @return Client
- */
- public function getClient()
- {
- return $this->client;
- }
- /**
- * 设置 GuzzleHttp Client
- * @param Client $client
- * @return $this
- */
- public function setClient(Client $client)
- {
- $this->client = $client;
- return $this;
- }
- }
|