SearchDummyJson.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\Tag;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Http\Client\ConnectionException;
  6. use Illuminate\Support\Facades\Http;
  7. use Illuminate\Support\Str;
  8. abstract class SearchDummyJson extends Command
  9. {
  10. /**
  11. * Limit fetching data per iteration
  12. *
  13. * @var int
  14. */
  15. protected int $limit = 5;
  16. /**
  17. * Get or create tags ids from Tag model
  18. *
  19. * @param $tags
  20. * @return array
  21. */
  22. protected function getTagsIds($tags):array
  23. {
  24. $ids = [];
  25. foreach ($tags as $tag){
  26. $t = Tag::query()->firstOrCreate(['name' => $tag]);
  27. $ids[] = $t->id;
  28. }
  29. return $ids;
  30. }
  31. /**
  32. * Convert array keys from camelCase to snake_case
  33. *
  34. * @param $arr
  35. * @return array
  36. */
  37. protected function arrayKeysCamelToSnake($arr): array
  38. {
  39. $ret = [];
  40. foreach ($arr as $k => $v)
  41. $ret[Str::snake($k)] = $v;
  42. return $ret;
  43. }
  44. /**
  45. * Get data from DummyJSON by name
  46. *
  47. * @param $name
  48. * @param $q
  49. * @return array
  50. * @throws ConnectionException
  51. */
  52. protected function getJson($name, $q): array
  53. {
  54. $skip = $total = 0;
  55. $data = [];
  56. do{
  57. $response = Http::retry(10, 15)
  58. ->get('https://dummyjson.com/' . $name . '/search', ['q' => $q, 'limit' => $this->limit, 'skip' => $skip]);
  59. if($response->successful()){
  60. $data = array_merge($data, $response->json($name));
  61. $skip = $response->json('skip');
  62. $total = $response->json('total');
  63. $skip += $this->limit;
  64. $this->info('Received ' . count($data) . ' / ' . $total);
  65. } else {
  66. $this->error('Error on HTTP request!');
  67. }
  68. } while($skip < $total);
  69. return $data;
  70. }
  71. }