GetProducts.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\Product;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\Http;
  6. use Illuminate\Support\Str;
  7. class GetProducts extends Command
  8. {
  9. /**
  10. * The name and signature of the console command.
  11. *
  12. * @var string
  13. */
  14. protected $signature = 'app:get-products';
  15. /**
  16. * The console command description.
  17. *
  18. * @var string
  19. */
  20. protected $description = 'Get products from DummyJSON';
  21. /**
  22. * Execute the console command.
  23. */
  24. public function handle()
  25. {
  26. $url = 'https://dummyjson.com/products/search';
  27. $limit = 5;
  28. $skip = 0;
  29. $total = 0;
  30. do{
  31. $response = Http::retry(10, 15)
  32. ->get($url, ['q' => 'iphone', 'limit' => $limit, 'skip' => $skip]);
  33. if($response->successful()){
  34. $json = $response->json();
  35. $products = $response->json('products');
  36. $skip = $response->json('skip');
  37. $total = $response->json('total');
  38. $this->upsertProducts($products);
  39. $skip += $limit;
  40. $this->info('Received ' . count($products) . ' records');
  41. } else {
  42. $this->error('Error on HTTP request!');
  43. }
  44. } while($skip < $total);
  45. $this->info('Total: ' . $total);
  46. }
  47. protected function upsertProducts($products):void
  48. {
  49. foreach ($products as $product){
  50. $tags = $product['tags'];
  51. // $reviews =
  52. $product = $this->arrayKeysCamelToSnake($product);
  53. Product::query()->updateOrInsert(['id' => $product['id']], $product);
  54. }
  55. }
  56. protected function arrayKeysCamelToSnake($arr): array
  57. {
  58. $ret = [];
  59. foreach ($arr as $k => $v)
  60. $ret[Str::snake($k)] = $v;
  61. return $ret;
  62. }
  63. }