Browse code

POC insert product

Benjamin Roth authored on21/10/2024 18:51:47
Showing1 changed files
... ...
@@ -185,4 +185,73 @@ class Shopware
185 185
 
186 186
         return $this->sendRequest($strUrlFragment,$options,$strMethod);
187 187
     }
188
+
189
+    protected function checkBySkuIfExists(string $strSku): bool
190
+    {
191
+        $Result = $this->getProductsForSku($strSku,false,true);
192
+
193
+        if ($Result->getStatusCode() == 200)
194
+        {
195
+            $Content = json_decode($Result->getContent());
196
+
197
+            if ($Content->total)
198
+            {
199
+                return true;
200
+            }
201
+        }
202
+        return false;
203
+    }
204
+
205
+    public function addOrUpdateProductBySku(string $strSku, array $arrData)/*: bool*/
206
+    {
207
+        // Update or insert check
208
+        $blnInsert = !$this->checkBySkuIfExists($strSku);
209
+
210
+        // Prepare product data
211
+        $arrData = [
212
+            'taxId' => '018e65c0485071508949c072f8dc18bd',
213
+            'id' => $this->createUuid(),
214
+            'price' => [
215
+                [
216
+                    'currencyId' => 'b7d2554b0ce847cd82f3ac9bd1c0dfca',
217
+                    'gross' => 9.9,
218
+                    'net' => 0,
219
+                    'linked' => true
220
+                ]
221
+            ],
222
+            'productNumber' => $strSku,
223
+            'stock' => 9999999,
224
+            'name' => 'Superheldenumhang'
225
+        ];
226
+
227
+        $options = [
228
+            'headers' => [
229
+                $this->getAuthentication(),
230
+                'Content-Type: application/json',
231
+                'Accept: application/json'
232
+            ],
233
+            'body' => json_encode($arrData)
234
+        ];
235
+
236
+        if ($blnInsert)
237
+        {
238
+            $response = $this->sendRequest('product',$options,'POST');
239
+        }
240
+
241
+        return $response->getStatusCode() == 200;
242
+    }
243
+
244
+    protected function createUuid($data = null) {
245
+        // Generate 16 bytes (128 bits) of random data or use the data passed into the function.
246
+        $data = $data ?? random_bytes(16);
247
+        assert(strlen($data) == 16);
248
+
249
+        // Set version to 0100
250
+        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
251
+        // Set bits 6-7 to 10
252
+        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
253
+
254
+        // Output the 36 character UUID.
255
+        return bin2hex($data);
256
+    }
188 257
 }