HttpRequestGraphQL.php 1.07 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
<?php
/**
 * Created by PhpStorm.
 * User: Zero
 * Time: 2021/1/11 10:10
 */

namespace Meibuyu\Micro\Shopify\tools;

use Meibuyu\Micro\Tools\CurlRequest;
use Meibuyu\Micro\Tools\HttpRequestJson;

class HttpRequestGraphQL extends HttpRequestJson
{

    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];
    }

    public static function post($url, $data, $headers = [], $variables = null)
    {
        [$headers, $postDataGraphQL] = self::prepareRequest($headers, $data, $variables);
        return CurlRequest::post($url, $postDataGraphQL, $headers);
    }

}