Skip to content

Commit

Permalink
Merge 4e2d57a into 71c6d49
Browse files Browse the repository at this point in the history
  • Loading branch information
Nathan Norton committed Oct 27, 2016
2 parents 71c6d49 + 4e2d57a commit 4e6a090
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ composer.lock
*.sh
script/*

# IDE
.idea

# Testing
/phpunit.xml
/build
Expand Down
33 changes: 33 additions & 0 deletions src/Bigcommerce/Api/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@ class Connection
*/
private $contentType;

/**
* Total number of times to automatically retry request if API rate limit is reached.
*/
private $maxRetries = 3;

/**
* Number of times request has been retried.
*/
private $autoRetries = 0;

/**
* Initializes the connection object.
*/
Expand Down Expand Up @@ -281,6 +291,13 @@ private function handleResponse()

$status = $this->getStatus();

if ($this->apiRateLimitReached($status)) {
if ($this->autoRetries < $this->maxRetries) {
$this->autoRetries++;
return $this->replayRequest();
}
}

if ($status >= 400 && $status <= 499) {
if ($this->failOnError) {
throw new ClientError($body, $status);
Expand All @@ -297,13 +314,29 @@ private function handleResponse()
}
}

$this->autoRetries = 0;

if ($this->followLocation) {
$this->followRedirectPath();
}

return $body;
}

public function apiRateLimitReached($status)
{
return $status == 429;
}

public function replayRequest()
{
$secondsToWait = $this->getHeader('X-Retry-After');
sleep($secondsToWait);
curl_exec($this->curl);

$this->handleResponse();
}

/**
* Return an representation of an error returned by the last request, or false
* if the last request was not an error.
Expand Down

0 comments on commit 4e6a090

Please sign in to comment.