Explorar el Código

created command - debugging

Alexander Musikhin hace 1 año
padre
commit
27764096fa
Se han modificado 2 ficheros con 78 adiciones y 0 borrados
  1. 77 0
      app/Console/Commands/GetProducts.php
  2. 1 0
      app/Models/Product.php

+ 77 - 0
app/Console/Commands/GetProducts.php

@@ -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;
+    }
+}

+ 1 - 0
app/Models/Product.php

@@ -8,6 +8,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsToMany;
 class Product extends Model
 {
     protected $fillable = [
+        'id',
         'title',
         'description',
         'category',