Client.php 2.4 KB
<?php


namespace Lackoxygen\Customs;

use GuzzleHttp\Client as GuzzleHttp;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\RequestOptions;
use Lackoxygen\Customs\Contract\RequestInterface;
use Lackoxygen\Customs\Exception\Exception;
use Psr\Http\Message\ResponseInterface;

class Client
{
    /**
     * @var GuzzleHttp
     */
    protected $guzzleHttp;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * Client constructor.
     */
    protected function __construct(RequestInterface $request)
    {
        $clientConfig     = (array)config('customs.client', [
            'timeout' => 30
        ]);
        $config           = $clientConfig + [
                'base_uri' => config('customs.host')
            ];
        $this->guzzleHttp = new GuzzleHttp($config);
        $this->request    = $request;
    }

    /**
     * @return ResponseInterface
     * @throws GuzzleException
     */
    protected function send(): ResponseInterface
    {
        return $this->guzzleHttp->request($this->request->getMethod(), $this->request->getPath(), $this->getOptions());
    }

    /**
     * @return array
     */
    protected function getOptions(): array
    {
        $requestArray = ['payExInfoStr' => $this->request->toJson(JSON_UNESCAPED_UNICODE)];
        $options      = [];
        if ($this->request->getMethod() === "GET") {
            $options[RequestOptions::QUERY] = $requestArray;
        } elseif ($this->request->getContentType() === 'application/x-www-form-urlencoded') {
            $options[RequestOptions::FORM_PARAMS] = $requestArray;
            $options[RequestOptions::HEADERS]     = ['Content-Type' => 'application/x-www-form-urlencoded'];
        } elseif (strpos($this->request->getContentType(), 'application/json') !== false) {
            $options[RequestOptions::JSON]    = $requestArray;
            $options[RequestOptions::HEADERS] = ['Content-Type' => 'application/json'];
        }

        return $options;
    }


    /**
     * @param RequestInterface $request
     *
     * @return string
     * @throws Exception
     */
    public static function request(RequestInterface $request): string
    {
        $client = new static($request);

        try {
            $response = $client->send();
        } catch (\Throwable $e) {
            throw new Exception($e);
        }
        $content = $response->getBody()->getContents();

        $response->getBody()->rewind();

        return $content;
    }
}