HttpRequestGraphQL.php 1.32 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php
/**
 * Created by PhpStorm.
 * User: Zero
 * Time: 2021/1/11 10:10
 */

namespace Meibuyu\Micro\Shopify\tools;

10
use Exception;
11

12
class HttpRequestGraphQL
13 14
{

15 16 17 18 19 20 21 22
    /**
     * @param array $headers
     * @param array $data
     * @param null $variables
     * @return array
     * @throws Exception
     * @author zero
     */
23 24 25 26 27
    protected static function prepareRequest($headers = [], $data = [], $variables = null)
    {
        if (is_string($data)) {
            $postDataGraphQL = $data;
        } else {
28
            throw new Exception("Only GraphQL string is allowed!");
29 30 31 32 33 34 35 36 37 38
        }
        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];
    }

39 40 41 42 43 44 45 46 47
    /**
     * @param $url
     * @param $data
     * @param array $headers
     * @param null $variables
     * @return array
     * @throws Exception
     * @author zero
     */
48 49 50 51 52 53 54
    public static function post($url, $data, $headers = [], $variables = null)
    {
        [$headers, $postDataGraphQL] = self::prepareRequest($headers, $data, $variables);
        return CurlRequest::post($url, $postDataGraphQL, $headers);
    }

}