<?php
/**
 * Created by PhpStorm.
 * User: Zero
 * Time: 2021/1/11 10:10
 */

namespace Meibuyu\Micro\Shopify\tools;

use Exception;

class HttpRequestGraphQL
{

    /**
     * @param array $headers
     * @param array $data
     * @param null $variables
     * @return array
     * @throws Exception
     * @author zero
     */
    protected static function prepareRequest($headers = [], $data = [], $variables = null)
    {
        if (is_string($data)) {
            $postDataGraphQL = $data;
        } else {
            throw new Exception("Only GraphQL string is allowed!");
        }
        if (is_array($variables)) {
            $postDataGraphQL = json_encode(['query' => $data, 'variables' => $variables]);
            $headers['Content-type'] = 'application/json';
        } else {
            $headers['Content-type'] = 'application/graphql';
        }
        return [$headers, $postDataGraphQL];
    }

    /**
     * @param $url
     * @param $data
     * @param array $headers
     * @param null $variables
     * @return array
     * @throws Exception
     * @author zero
     */
    public static function post($url, $data, $headers = [], $variables = null)
    {
        [$headers, $postDataGraphQL] = self::prepareRequest($headers, $data, $variables);
        return CurlRequest::post($url, $postDataGraphQL, $headers);
    }

}