Commit 366458dd authored by 王源's avatar 王源 🎧

优化curl请求

parent 1c23d31d
...@@ -9,27 +9,17 @@ class CurlRequest ...@@ -9,27 +9,17 @@ class CurlRequest
protected static function init($url, $httpHeaders = []) protected static function init($url, $httpHeaders = [])
{ {
// Create Curl resource
$ch = curl_init(); $ch = curl_init();
// Set URL
curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_URL, $url);
//Return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'PHPClassic/PHPShopify'); curl_setopt($ch, CURLOPT_USERAGENT, 'PHPClassic/PHPShopify');
$headers = []; $headers = [];
foreach ($httpHeaders as $key => $value) { foreach ($httpHeaders as $key => $value) {
$headers[] = "$key: $value"; $headers[] = "$key: $value";
} }
//Set HTTP Headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
return $ch; return $ch;
} }
public static function get($url, $httpHeaders = []) public static function get($url, $httpHeaders = [])
...@@ -63,35 +53,20 @@ class CurlRequest ...@@ -63,35 +53,20 @@ class CurlRequest
protected static function processRequest($ch) protected static function processRequest($ch)
{ {
# Check for 429 leaky bucket error $output = curl_exec($ch);
while (1) { $response = new CurlResponse($output);
$output = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$response = new CurlResponse($output); if ($httpCode == 429) {
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode != 429) {
break;
}
$limitHeader = explode('/', $response->getHeader('X-Shopify-Shop-Api-Call-Limit'), 2); $limitHeader = explode('/', $response->getHeader('X-Shopify-Shop-Api-Call-Limit'), 2);
if (isset($limitHeader[1]) && $limitHeader[0] < $limitHeader[1]) { if (isset($limitHeader[1]) && $limitHeader[0] < $limitHeader[1]) {
throw new Exception($response->getBody()); throw new Exception($response->getBody());
} }
usleep(500000);
} }
if (curl_errno($ch)) { if (curl_errno($ch)) {
throw new Exception(curl_errno($ch) . ' : ' . curl_error($ch)); throw new Exception(curl_errno($ch) . ' : ' . curl_error($ch));
} }
// close curl resource to free up system resources
curl_close($ch); curl_close($ch);
return [$httpCode, $response->getHeaders(), $response->getBody()];
$httpHeader = $response->getHeaders();
return [$httpCode, $httpHeader, $response->getBody()];
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment