| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <?php
- namespace App\Console\Commands;
- use App\Models\Tag;
- use Illuminate\Console\Command;
- use Illuminate\Http\Client\ConnectionException;
- use Illuminate\Support\Facades\Http;
- use Illuminate\Support\Str;
- abstract class SearchDummyJson extends Command
- {
- /**
- * Limit fetching data per iteration
- *
- * @var int
- */
- protected int $limit = 5;
- /**
- * Get or create tags ids from Tag model
- *
- * @param $tags
- * @return array
- */
- protected function getTagsIds($tags):array
- {
- $ids = [];
- foreach ($tags as $tag){
- $t = Tag::query()->firstOrCreate(['name' => $tag]);
- $ids[] = $t->id;
- }
- return $ids;
- }
- /**
- * Convert array keys from camelCase to snake_case
- *
- * @param $arr
- * @return array
- */
- protected function arrayKeysCamelToSnake($arr): array
- {
- $ret = [];
- foreach ($arr as $k => $v)
- $ret[Str::snake($k)] = $v;
- return $ret;
- }
- /**
- * Get data from DummyJSON by name
- *
- * @param $name
- * @param $q
- * @return array
- * @throws ConnectionException
- */
- protected function getJson($name, $q): array
- {
- $skip = $total = 0;
- $data = [];
- do{
- $response = Http::retry(10, 15)
- ->get('https://dummyjson.com/' . $name . '/search', ['q' => $q, 'limit' => $this->limit, 'skip' => $skip]);
- if($response->successful()){
- $data = array_merge($data, $response->json($name));
- $skip = $response->json('skip');
- $total = $response->json('total');
- $skip += $this->limit;
- $this->info('Received ' . count($data) . ' / ' . $total);
- } else {
- $this->error('Error on HTTP request!');
- }
- } while($skip < $total);
- return $data;
- }
- }
|