44
55use BigCommerce \ApiV3 \Client ;
66use BigCommerce \ApiV3 \ResponseModels \PaginatedResponse ;
7+ use GuzzleHttp \Exception \RequestException ;
78use GuzzleHttp \RequestOptions ;
9+ use Psr \Http \Client \RequestExceptionInterface ;
810use Psr \Http \Message \ResponseInterface ;
11+ use RuntimeException ;
912
1013trait BatchUpdateResource
1114{
1215 abstract public function batchUpdate (array $ resources ): PaginatedResponse ;
1316 abstract protected function multipleResourcesEndpoint (): string ;
1417 abstract public function getClient (): Client ;
1518
19+ private int $ maxRetries = 0 ;
20+
1621 protected function maxBatchSize (): int
1722 {
1823 return 10 ;
@@ -21,20 +26,46 @@ protected function maxBatchSize(): int
2126 /**
2227 * @param array $resources
2328 * @return ResponseInterface[]
29+ * @throws RequestExceptionInterface
2430 */
2531 protected function batchUpdateResource (array $ resources ): array
2632 {
2733 $ chunks = array_chunk ($ resources , $ this ->maxBatchSize ());
28- $ responses = [];
29- foreach ($ chunks as $ chunk ) {
30- $ responses [] = $ this ->getClient ()->getRestClient ()->put (
31- $ this ->multipleResourcesEndpoint (),
32- [
33- RequestOptions::JSON => $ chunk ,
34- ]
35- );
34+ return array_map (fn ($ chunk ) => $ this ->putRequestWithRetries ($ chunk ), $ chunks );
35+ }
36+
37+ private function putRequestWithRetries ($ data ): ResponseInterface
38+ {
39+ $ retriesRemaining = $ this ->getMaxRetries () + 1 ;
40+
41+ while ($ retriesRemaining -- > 0 ) {
42+ try {
43+ return $ this ->getClient ()->getRestClient ()->put (
44+ $ this ->multipleResourcesEndpoint (),
45+ [
46+ RequestOptions::JSON => $ data ,
47+ ]
48+ );
49+ } catch (\Exception $ exception ) {
50+ if (!in_array ($ exception ->getCode (), $ this ->retryOnErrorCodes ()) || $ retriesRemaining <= 0 ) {
51+ throw $ exception ;
52+ }
53+ }
3654 }
55+ }
3756
38- return $ responses ;
57+ protected function retryOnErrorCodes (): array
58+ {
59+ return [500 , 502 , 503 , 504 ];
60+ }
61+
62+ public function getMaxRetries (): int
63+ {
64+ return $ this ->maxRetries ;
65+ }
66+
67+ public function setMaxRetries (int $ maxRetries ): void
68+ {
69+ $ this ->maxRetries = $ maxRetries ;
3970 }
4071}
0 commit comments