From f7f98bece9c29214520b9263dafa2554b8c76bf5 Mon Sep 17 00:00:00 2001 From: Jan Myszkier Date: Sun, 15 Apr 2018 18:05:23 +0200 Subject: [PATCH] add simple bucket handling to avoid Response code 409 --- lib/ShopifyResource.php | 49 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/lib/ShopifyResource.php b/lib/ShopifyResource.php index 0f2808a..3d5922e 100644 --- a/lib/ShopifyResource.php +++ b/lib/ShopifyResource.php @@ -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 * @@ -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); @@ -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); @@ -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); @@ -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); @@ -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; + } + + } \ No newline at end of file