CurlRequest.php 2.18 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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
<?php

namespace Meibuyu\Micro\Tools;

use Exception;

class CurlRequest
{

    protected static function init($url, $httpHeaders = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, 'PHPClassic/PHPShopify');
        $headers = [];
        foreach ($httpHeaders as $key => $value) {
            $headers[] = "$key: $value";
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        return $ch;
    }

    public static function get($url, $httpHeaders = [])
    {
        $ch = self::init($url, $httpHeaders);
        return self::processRequest($ch);
    }

    public static function post($url, $data, $httpHeaders = [])
    {
        $ch = self::init($url, $httpHeaders);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        return self::processRequest($ch);
    }

    public static function put($url, $data, $httpHeaders = [])
    {
        $ch = self::init($url, $httpHeaders);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        return self::processRequest($ch);
    }

    public static function delete($url, $httpHeaders = [])
    {
        $ch = self::init($url, $httpHeaders);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
        return self::processRequest($ch);
    }

    protected static function processRequest($ch)
    {
王源's avatar
王源 committed
56 57 58 59
        $output = curl_exec($ch);
        $response = new CurlResponse($output);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($httpCode == 429) {
60 61 62 63 64 65 66 67 68
            $limitHeader = explode('/', $response->getHeader('X-Shopify-Shop-Api-Call-Limit'), 2);
            if (isset($limitHeader[1]) && $limitHeader[0] < $limitHeader[1]) {
                throw new Exception($response->getBody());
            }
        }
        if (curl_errno($ch)) {
            throw new Exception(curl_errno($ch) . ' : ' . curl_error($ch));
        }
        curl_close($ch);
王源's avatar
王源 committed
69
        return [$httpCode, $response->getHeaders(), $response->getBody()];
70 71 72
    }

}