|
|
@@ -0,0 +1,77 @@
|
|
|
+<?php
|
|
|
+
|
|
|
+namespace App\Console\Commands;
|
|
|
+
|
|
|
+use App\Models\Product;
|
|
|
+use Illuminate\Console\Command;
|
|
|
+use Illuminate\Support\Facades\Http;
|
|
|
+use Illuminate\Support\Str;
|
|
|
+
|
|
|
+class GetProducts extends Command
|
|
|
+{
|
|
|
+ /**
|
|
|
+ * The name and signature of the console command.
|
|
|
+ *
|
|
|
+ * @var string
|
|
|
+ */
|
|
|
+ protected $signature = 'app:get-products';
|
|
|
+
|
|
|
+ /**
|
|
|
+ * The console command description.
|
|
|
+ *
|
|
|
+ * @var string
|
|
|
+ */
|
|
|
+ protected $description = 'Get products from DummyJSON';
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Execute the console command.
|
|
|
+ */
|
|
|
+ public function handle()
|
|
|
+ {
|
|
|
+ $url = 'https://dummyjson.com/products/search';
|
|
|
+ $limit = 5;
|
|
|
+ $skip = 0;
|
|
|
+ $total = 0;
|
|
|
+
|
|
|
+ do{
|
|
|
+ $response = Http::retry(10, 15)
|
|
|
+ ->get($url, ['q' => 'iphone', 'limit' => $limit, 'skip' => $skip]);
|
|
|
+ if($response->successful()){
|
|
|
+ $json = $response->json();
|
|
|
+ $products = $response->json('products');
|
|
|
+ $skip = $response->json('skip');
|
|
|
+ $total = $response->json('total');
|
|
|
+
|
|
|
+ $this->upsertProducts($products);
|
|
|
+
|
|
|
+
|
|
|
+ $skip += $limit;
|
|
|
+ $this->info('Received ' . count($products) . ' records');
|
|
|
+ } else {
|
|
|
+ $this->error('Error on HTTP request!');
|
|
|
+
|
|
|
+ }
|
|
|
+ } while($skip < $total);
|
|
|
+ $this->info('Total: ' . $total);
|
|
|
+ }
|
|
|
+
|
|
|
+ protected function upsertProducts($products):void
|
|
|
+ {
|
|
|
+ foreach ($products as $product){
|
|
|
+
|
|
|
+ $tags = $product['tags'];
|
|
|
+// $reviews =
|
|
|
+
|
|
|
+ $product = $this->arrayKeysCamelToSnake($product);
|
|
|
+ Product::query()->updateOrInsert(['id' => $product['id']], $product);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ protected function arrayKeysCamelToSnake($arr): array
|
|
|
+ {
|
|
|
+ $ret = [];
|
|
|
+ foreach ($arr as $k => $v)
|
|
|
+ $ret[Str::snake($k)] = $v;
|
|
|
+ return $ret;
|
|
|
+ }
|
|
|
+}
|