<?php

namespace app\admin\service\tools\requester\impl;

use app\admin\service\tools\requester\IHttpRequester;
use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;

class GuzzleHttpRequester implements IHttpRequester
{
    /** guzzle http 客户端 */
    protected Client $client;

    public function __construct()
    {
        $this->client = new Client();
    }
    public function get(string $url, $params = [], ?array $header = [], ?array $options = [])
    {
        $response = $this->client->get(
            $url,
            array_merge(
                [
                    'headers' => $header,
                    'query' => $params,
                    'verify' => false
                ],
                $options
            )
        );

        return $this->array($response);
    }

    public function post(string $url, $data = [], ?array $header = [], ?array $options = [])
    {
        $response = $this->client->post(
            $url,
            array_merge(
                [
                    'headers' => $header,
                    'json' => $data,
                    'verify' => false
                ],
                $options
            )
        );

        return $this->array($response);
    }

    public function put(string $url, $data = [], ?array $header = [], ?array $options = [])
    {
        $response = $this->client->put(
            $url,
            array_merge(
                [
                    'headers' => $header,
                    'json' => $data,
                    'verify' => false
                ],
                $options
            )
        );

        return $this->array($response);
    }

    public function patch(string $url, $data = [], ?array $header = [], ?array $options = [])
    {
        $response = $this->client->patch(
            $url,
            array_merge(
                [
                    'headers' => $header,
                    'json' => $data,
                    'verify' => false
                ],
                $options
            )
        );

        return $this->array($response);
    }

    public function delete(string $url, $params = [], ?array $header = [], ?array $options = [])
    {
        $response = $this->client->delete(
            $url,
            array_merge(
                [
                    'headers' => $header,
                    'query' => $params,
                    'verify' => false
                ],
                $options
            )
        );

        return $this->array($response);
    }

    /**
     * 返回数组
     *
     * @param ResponseInterface $response
     * @return array
     */
    protected function array(ResponseInterface $response)
    {
        return json_decode($response->getBody()->getContents(), true);
    }
}