From 301c9f029d6406ef58d948a646664294e57aa05e Mon Sep 17 00:00:00 2001 From: Elmer Thomas Date: Fri, 9 Mar 2018 11:39:10 -0800 Subject: [PATCH] Fix #88: Missing Function --- lib/Client.php | 43 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/lib/Client.php b/lib/Client.php index a496a15..aa381a2 100644 --- a/lib/Client.php +++ b/lib/Client.php @@ -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. @@ -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; }