Skip to content
49 changes: 46 additions & 3 deletions lib/ShopifyResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@
*/
abstract class ShopifyResource
{
/**
* @see: https://help.shopify.com/api/getting-started/api-call-limit
* @var int
*/
private $apiBucketLimit = 40;
private $apiCallBucket;

/**
* HTTP request headers
*
Expand Down Expand Up @@ -303,6 +310,9 @@ public function generateUrl($urlParams = array(), $customAction = null)
public function get($urlParams = array(), $url = null, $dataKey = null)
{
if (!$url) $url = $this->generateUrl($urlParams);
while($this->isBucketFull()){
sleep(1);
}

$response = HttpRequestJson::get($url, $this->httpHeaders);

Expand Down Expand Up @@ -367,7 +377,9 @@ public function post($dataArray, $url = null)
if (!$url) $url = $this->generateUrl();

if (!empty($dataArray)) $dataArray = $this->wrapData($dataArray);

while($this->isBucketFull()){
sleep(1);
}
$response = HttpRequestJson::post($url, $dataArray, $this->httpHeaders);

return $this->processResponse($response, $this->resourceKey);
Expand All @@ -389,7 +401,9 @@ public function put($dataArray, $url = null)
if (!$url) $url = $this->generateUrl();

if (!empty($dataArray)) $dataArray = $this->wrapData($dataArray);

while($this->isBucketFull()){
sleep(1);
}
$response = HttpRequestJson::put($url, $dataArray, $this->httpHeaders);

return $this->processResponse($response, $this->resourceKey);
Expand All @@ -408,7 +422,9 @@ public function put($dataArray, $url = null)
public function delete($urlParams = array(), $url = null)
{
if (!$url) $url = $this->generateUrl($urlParams);

while($this->isBucketFull()){
sleep(1);
}
$response = HttpRequestJson::delete($url, $this->httpHeaders);

return $this->processResponse($response);
Expand Down Expand Up @@ -498,4 +514,31 @@ public function processResponse($responseArray, $dataKey = null)
return $responseArray;
}
}

public function isBucketFull()
{
//clear old bucket contents
if(!empty($this->apiCallBucket)) {
$this->apiCallBucket = array_filter(
$this->apiCallBucket, function ($apiCallTimeStamp) {
/* Bucket leaks each second */
return ($apiCallTimeStamp < time()-1);
}
);
}

//
if (empty($this->apiCallBucket)){
return false;
}

//check if 40 elements left
if(count($this->apiCallBucket) == $this->apiBucketLimit){
return true;
}

return false;
}


}