<?php

namespace App\Services\Vendor\BaiduAi;

use Ixudra\Curl\Facades\Curl;

class Request
{

    /**
     * @param  string  $url
     * @param  array  $data  HTTP POST BODY
     * @param  array  $params
     * @param  array  $headers  HTTP header
     * @return array
     */
    public function post($url, $data = array(), $params = array(), $headers = array())
    {
        $url = $this->buildUrl($url, $params);
        $headers = $this->buildHeaders($headers);
        $response = Curl::to($url)->withData($data)->withHeaders($headers)->asJsonResponse(true)->post();

        return $response;
    }

    /**
     *
     * @param  string  $url
     * @param  array  $params  参数
     * @return string
     */
    private function buildUrl($url, $params)
    {
        if (!empty($params)) {
            $str = http_build_query($params);

            return $url . (strpos($url, '?') === false ? '?' : '&') . $str;
        } else {
            return $url;
        }
    }

    /**
     * 构造 header
     * @param  array  $headers
     * @return array
     */
    private function buildHeaders($headers)
    {
        $result = array();
        foreach ($headers as $k => $v) {
            $result[] = sprintf('%s:%s', $k, $v);
        }

        return $result;
    }

    /**
     * @param  string  $url
     * @param  array  $params
     * @param  array  $headers  HTTP header
     * @return array
     */
    public function get($url, $params = array(), $headers = array())
    {
        $url = $this->buildUrl($url, $params);
        $headers = $this->buildHeaders($headers);

        $response = Curl::to($url)->asJsonResponse(true)->get();

        return $response;
    }
}
