Skip to content

Commit

Permalink
Add force update
Browse files Browse the repository at this point in the history
  • Loading branch information
znck committed Mar 15, 2016
1 parent 1bec2d0 commit a78a2b3
Showing 1 changed file with 22 additions and 28 deletions.
50 changes: 22 additions & 28 deletions src/UpdateCountriesCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class UpdateCountriesCommand extends Command
*
* @var string
*/
protected $signature = 'countries:update';
protected $signature = 'countries:update {--f|force : Force update}';

/**
* The console command description.
Expand Down Expand Up @@ -99,7 +99,7 @@ public function handle()

$hash = md5($countries->toJson());

if ($hash === $this->hash) {
if (!$this->option('force') && $hash === $this->hash) {
$this->line("No new country.");
return false;
}
Expand All @@ -110,38 +110,32 @@ public function handle()
DB::table($this->countries)->whereIn('code', $countryCodes)->pluck('id', 'code')
);

$countries->map(
function ($item) use ($existingCountryIDs) {
if ($existingCountryIDs->has($item['code'])) {
$item['id'] = $existingCountryIDs->get($item['code']);
}

return $item;
$countries = $countries->map(function ($item) use ($existingCountryIDs) {
if ($existingCountryIDs->has($item['code'])) {
$item['id'] = $existingCountryIDs->get($item['code']);
}
);

$countries = $countries->groupBy(
function ($item) {
return array_has($item, 'id') ? 'update' : 'create';
}
);
return $item;
});

DB::transaction(
function () use ($countries, $hash) {
$create = Collection::make($countries->get('create'));
$update = Collection::make($countries->get('update'));
$countries = $countries->groupBy(function ($item) {
return array_has($item, 'id') ? 'update' : 'create';
});

foreach ($create->chunk(static::QUERY_LIMIT) as $entries) {
DB::table($this->countries)->insert($entries->toArray());
}
DB::transaction(function () use ($countries, $hash) {
$create = $countries->get('create', Collection::make());
$update = $countries->get('update', Collection::make());

foreach ($update->chunk(static::QUERY_LIMIT) as $entries) {
DB::table($this->countries)->update($entries->toArray());
}
$this->line("{$create->count()} countries created. {$update->count()} countries updated.");
$this->files->put(storage_path(static::INSTALL_HISTORY), $hash);
foreach ($create->chunk(static::QUERY_LIMIT) as $entries) {
DB::table($this->countries)->insert($entries->toArray());
}
);

foreach ($update as $entries) {
DB::table($this->countries)->where('id', $entries['id'])->update($entries);
}
$this->line("{$create->count()} countries created. {$update->count()} countries updated.");
$this->files->put(storage_path(static::INSTALL_HISTORY), $hash);
});

return true;
}
Expand Down

0 comments on commit a78a2b3

Please sign in to comment.