WeatherCommands.php in Weather 8
File
src/Commands/WeatherCommands.php
View source
<?php
namespace Drupal\weather\Commands;
use Drush\Commands\DrushCommands;
class WeatherCommands extends DrushCommands {
private $items;
public function import() {
$this
->del()
->read()
->add()
->logger()
->success(dt('Ok.'));
}
private function del() : self {
$all = $this
->store()
->loadByProperties([
'status' => 'original',
]);
$i = 0;
$c = count($all);
foreach ($all as $del) {
$del
->delete();
if (++$i % 50 === 0) {
$this
->logger()
->info("del {$i} / {$c}");
}
}
return $this;
}
private function csv() {
return fopen(drupal_get_path('module', 'weather') . '/files/weather_data.csv', 'r');
}
private function store() {
return \Drupal::service('entity_type.manager')
->getStorage('weather_place');
}
private function read() : self {
$file = $this
->csv();
$i = 0;
$items = [];
while (($line = fgetcsv($file, 0, ' ')) !== FALSE) {
$items[] = $line;
if (++$i % 500 === 0) {
$this
->logger()
->info("read {$i}");
}
}
fclose($file);
$this->items = $items;
return $this;
}
private function add() : self {
$s = $this
->store();
$i = 0;
$c = count($this->items);
$this
->logger()
->info("will add: {$c}");
foreach ($this->items as $item) {
$s
->create([
'geoid' => $item[0],
'latitude' => $item[1],
'longitude' => $item[2],
'country' => $item[3],
'name' => $item[4],
'link' => trim($item[5]),
'status' => 'original',
])
->save();
if (++$i % 50 === 0) {
$this
->logger()
->success("add {$i} / {$c}");
}
}
return $this;
}
}
Classes
Name |
Description |
WeatherCommands |
Drush command to add support to weather module (import weather csv file). |