Skip to content

Fix #88: Missing Function #89

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 9, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 39 additions & 4 deletions lib/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,43 @@ private function createCurlMultiHandle($requests)
return [$channels, $multiHandle];
}

/**
* Prepare response object
*
* @param resource $curl the curl resource
*
* @return Response object
*/
private function prepareResponse($curl)
{
$response = curl_exec($curl);
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$responseBody = substr($response, $headerSize);
$responseHeaders = substr($response, 0, $headerSize);
$responseHeaders = explode("\n", $responseHeaders);
$responseHeaders = array_map('trim', $responseHeaders);
$response = new Response($statusCode, $responseBody, $responseHeaders);
return $response;
}
/**
* Retry request
*
* @param array $responseHeaders headers from rate limited response
* @param string $method the HTTP verb
* @param string $url the final url to call
* @param array $body request body
* @param array $headers original headers
*
* @return Response response object
*/
private function retryRequest($responseHeaders, $method, $url, $body, $headers)
{
$sleepDurations = $responseHeaders['X-Ratelimit-Reset'] - time();
sleep($sleepDurations > 0 ? $sleepDurations : 0);
return $this->makeRequest($method, $url, $body, $headers, false);
}

/**
* Make the API call and return the response. This is separated into
* it's own function, so we can mock it easily for testing.
Expand All @@ -260,16 +297,14 @@ public function makeRequest($method, $url, $body = null, $headers = null, $retry

curl_setopt_array($curl, $curlOpts);

curl_setopt($curl, CURLOPT_HTTPHEADER, $this->headers);

$response = $this->prepareResponse($curl);

curl_close($curl);

if ($response->statusCode() == 429 && $retryOnLimit) {
return $this->retryRequest($response->headers(true), $method, $url, $body, $headers);
}

curl_close($curl);

return $response;
}

Expand Down