2019-08-08 06:12:59 +00:00
|
|
|
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
|
|
|
|
use Illuminate\Console\Command;
|
|
|
|
use App\Place;
|
|
|
|
use DB;
|
|
|
|
use Illuminate\Support\Str;
|
|
|
|
|
|
|
|
class ImportCities extends Command
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* The name and signature of the console command.
|
|
|
|
*
|
|
|
|
* @var string
|
|
|
|
*/
|
2019-08-09 03:38:48 +00:00
|
|
|
protected $signature = 'import:cities {chunk=1000}';
|
2019-08-08 06:12:59 +00:00
|
|
|
/**
|
|
|
|
* The console command description.
|
|
|
|
*
|
|
|
|
* @var string
|
|
|
|
*/
|
|
|
|
protected $description = 'Import Cities to database';
|
|
|
|
/**
|
|
|
|
* Create a new command instance.
|
|
|
|
*
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
public function __construct()
|
|
|
|
{
|
|
|
|
parent::__construct();
|
|
|
|
}
|
|
|
|
/**
|
|
|
|
* Execute the console command.
|
|
|
|
*
|
|
|
|
* @return mixed
|
|
|
|
*/
|
|
|
|
public function handle()
|
|
|
|
{
|
|
|
|
$path = storage_path('app/cities.json');
|
2019-08-09 03:38:48 +00:00
|
|
|
if (!is_file($path)) {
|
2019-08-08 06:12:59 +00:00
|
|
|
$this->error('Missing storage/app/cities.json file!');
|
|
|
|
return;
|
|
|
|
}
|
2019-08-09 04:01:59 +00:00
|
|
|
if (Place::count() > 10) {
|
|
|
|
$this->error('Cities already imported, aborting operation...');
|
|
|
|
return;
|
|
|
|
}
|
2019-08-08 06:12:59 +00:00
|
|
|
$this->info('Importing city data into database ...');
|
|
|
|
$cities = file_get_contents($path);
|
|
|
|
$cities = json_decode($cities);
|
2019-08-09 03:38:48 +00:00
|
|
|
$cityCount = count($cities);
|
|
|
|
$this->info("Found {$cityCount} cities to insert ...");
|
|
|
|
$bar = $this->output->createProgressBar($cityCount);
|
2019-08-08 06:12:59 +00:00
|
|
|
$bar->start();
|
2019-08-09 03:38:48 +00:00
|
|
|
$buffer = [];
|
|
|
|
$count = 0;
|
2019-08-08 06:12:59 +00:00
|
|
|
foreach ($cities as $city) {
|
|
|
|
$country = $city->country == 'XK' ? 'Kosovo' : (new \League\ISO3166\ISO3166)->alpha2($city->country)['name'];
|
2019-08-09 03:38:48 +00:00
|
|
|
$buffer[] = ["name" => $city->name, "slug" => Str::slug($city->name), "country" => $country, "lat" => $city->lat, "long" => $city->lng];
|
|
|
|
$count++;
|
|
|
|
if ($count % $this->argument('chunk') == 0) {
|
|
|
|
$this->insertBuffer($buffer, $count);
|
|
|
|
$bar->advance(count($buffer));
|
|
|
|
$buffer = [];
|
|
|
|
}
|
2019-08-08 06:12:59 +00:00
|
|
|
}
|
2019-08-09 03:38:48 +00:00
|
|
|
$this->insertBuffer($buffer, $count);
|
2019-08-08 06:12:59 +00:00
|
|
|
$bar->finish();
|
2019-08-09 03:38:48 +00:00
|
|
|
$this->info('Successfully imported ' . $count . ' entries.');
|
2019-08-08 06:12:59 +00:00
|
|
|
return;
|
|
|
|
}
|
2019-08-09 03:38:48 +00:00
|
|
|
|
|
|
|
private function insertBuffer($buffer, $count)
|
|
|
|
{
|
|
|
|
DB::table('places')->insert($buffer);
|
|
|
|
}
|
2019-08-08 06:12:59 +00:00
|
|
|
}
|