ImportCities.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Place;
  5. use DB;
  6. use Illuminate\Support\Str;
  7. class ImportCities extends Command
  8. {
  9. /**
  10. * The name and signature of the console command.
  11. *
  12. * @var string
  13. */
  14. protected $signature = 'import:cities {chunk=1000}';
  15. /**
  16. * The console command description.
  17. *
  18. * @var string
  19. */
  20. protected $description = 'Import Cities to database';
  21. /**
  22. * Create a new command instance.
  23. *
  24. * @return void
  25. */
  26. public function __construct()
  27. {
  28. parent::__construct();
  29. }
  30. /**
  31. * Execute the console command.
  32. *
  33. * @return mixed
  34. */
  35. public function handle()
  36. {
  37. $path = storage_path('app/cities.json');
  38. if (!is_file($path)) {
  39. $this->error('Missing storage/app/cities.json file!');
  40. return;
  41. }
  42. // if (Place::count() > 10) {
  43. // $this->error('Cities already imported, aborting operation...');
  44. // return;
  45. // }
  46. $this->info('Importing city data into database ...');
  47. $cities = file_get_contents($path);
  48. $cities = json_decode($cities);
  49. $cityCount = count($cities);
  50. $this->info("Found {$cityCount} cities to insert ...");
  51. $bar = $this->output->createProgressBar($cityCount);
  52. $bar->start();
  53. $buffer = [];
  54. $count = 0;
  55. foreach ($cities as $city) {
  56. $country = $city->country == 'XK' ? 'Kosovo' : (new \League\ISO3166\ISO3166)->alpha2($city->country)['name'];
  57. $buffer[] = ["name" => $city->name, "slug" => Str::slug($city->name), "country" => $country, "lat" => $city->lat, "long" => $city->lng];
  58. $count++;
  59. if ($count % $this->argument('chunk') == 0) {
  60. $this->insertBuffer($buffer, $count);
  61. $bar->advance(count($buffer));
  62. $buffer = [];
  63. }
  64. }
  65. $this->insertBuffer($buffer, $count);
  66. $bar->finish();
  67. $this->info('Successfully imported ' . $count . ' entries.');
  68. return;
  69. }
  70. private function insertBuffer($buffer, $count)
  71. {
  72. DB::table('places')->insert($buffer);
  73. }
  74. }