SearchProducts.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\Product;
  4. use App\Models\ProductImage;
  5. use App\Models\ProductReview;
  6. use Illuminate\Http\Client\ConnectionException;
  7. class SearchProducts extends SearchDummyJson
  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(): void
  25. {
  26. try {
  27. $products = $this->getJson('products', 'iPhone');
  28. $this->upsertProducts($products);
  29. $this->info('Done!');
  30. } catch (ConnectionException $e) {
  31. $this->error('Error fetching data!');
  32. dump($e);
  33. }
  34. }
  35. /**
  36. * Prepare data and update or insert into DB
  37. * todo: need validation
  38. *
  39. * @param $products
  40. * @return void
  41. */
  42. protected function upsertProducts($products): void
  43. {
  44. foreach ($products as $product) {
  45. // remember foreign tables data
  46. $tags = $product['tags'];
  47. $reviews = $product['reviews'];
  48. $images = $product['images'];
  49. // move some subarray elements to root
  50. $product['width'] = $product['dimensions']['width'];
  51. $product['height'] = $product['dimensions']['height'];
  52. $product['depth'] = $product['dimensions']['depth'];
  53. $product['barcode'] = $product['meta']['barcode'];
  54. $product['qr_code'] = $product['meta']['qrCode'];
  55. // remove extra data
  56. unset($product['tags'], $product['reviews'], $product['images'], $product['dimensions'], $product['meta']);
  57. $product = $this->arrayKeysCamelToSnake($product);
  58. Product::query()->updateOrInsert(['id' => $product['id']], $product);
  59. $p = Product::find($product['id']);
  60. // detach all tags and attach received
  61. $p->tags()->detach();
  62. $p->tags()->attach($this->getTagsIds($tags));
  63. // delete all reviews and create from received
  64. ProductReview::query()->where('product_id', '=', $p->id)->delete();
  65. foreach ($reviews as $review) {
  66. $review['product_id'] = $p->id;
  67. ProductReview::query()->create($this->arrayKeysCamelToSnake($review));
  68. }
  69. // delete all images and create from received
  70. ProductImage::query()->where('product_id', '=', $p->id)->delete();
  71. foreach ($images as $image) {
  72. ProductImage::create(['product_id' => $p->id, 'url' => $image]);
  73. }
  74. }
  75. }
  76. }