public function DataService::weatherDataInstallation in Weather 2.0.x
Same name and namespace in other branches
- 8 src/Service/DataService.php \Drupal\weather\Service\DataService::weatherDataInstallation()
Helper function for installation and upgrades.
This function inserts data into the weather_place table.
The data file lists one table entry per line. Fields are separated by tab stops. The format is as follows:
GeoID Primary key, string. Currently supported keys are:
- GeoNames ID, prefixed with geonames_
- Sentralt stadnamnregister ID, prefixed with ssr_
(tab stop) Latitude -90 .. 90, Positive values for north, negative for south. (tab stop) Longitude -180 .. 180, Positive values for east, negative for west. (tab stop) Country (tab stop) Name (tab stop) Link to yr.no weather forecast (newline)
To save space, the link to the actual yr.no URL has been shortened. Every URL starts with "http://www.yr.no/place/", followed by the country.
In the country's name, every whitespace gets replaced with an underscore, all other characters are kept as they are. The only exception is the last dot in the following country:
"Virgin Islands, U.S." -> "Virgin_Islands,_U.S_"
File
- src/
Service/ DataService.php, line 89
Class
- DataService
- Installation, update and removal of weather places.
Namespace
Drupal\weather\ServiceCode
public function weatherDataInstallation() {
// Delete all original entries from the table, if any.
$deleteIds = $this->placeStorage
->getQuery()
->condition('status', WeatherPlaceInterface::STATUS_ORIGINAL)
->execute();
// Get all remaining entries in the table.
$changed_geoids = $this->placeStorage
->getQuery()
->condition('status', WeatherPlaceInterface::STATUS_ORIGINAL, '<>')
->execute();
// Read the data file and create Places in system.
$file = fopen(drupal_get_path('module', 'weather') . '/files/weather_data.csv', 'r');
$items = [];
while (($line = fgetcsv($file, 0, ' ')) !== FALSE) {
// Check if the geoid has been modified, if so, skip it.
if (!in_array($line[0], $changed_geoids)) {
$items[] = $line;
}
}
fclose($file);
$op = 'Importing';
if ($deleteIds) {
$op = 'Re-importing';
$this->batchBuilder
->addOperation([
self::class,
'processBatch',
], [
array_values($deleteIds),
'remove',
]);
}
$this->batchBuilder
->addOperation([
self::class,
'processBatch',
], [
$items,
'add',
]);
$this->batchBuilder
->setTitle($this
->t('@operation weather places', [
'@operation' => $op,
]))
->setInitMessage($this
->t('Weather places import is starting.'))
->setProgressMessage($this
->t('Processed @current out of @total.'))
->setErrorMessage($this
->t('Weather places import has encountered an error.'))
->setFinishCallback([
self::class,
'finishBatch',
]);
batch_set($this->batchBuilder
->toArray());
}