You are here

protected function ParserService::updatePlaces in Weather 2.0.x

Same name and namespace in other branches
  1. 8 src/Service/ParserService.php \Drupal\weather\Service\ParserService::updatePlaces()

Handle updates to the weather_places entity.

1 call to ParserService::updatePlaces()
ParserService::parseForecast in src/Service/ParserService.php
Parses an XML forecast supplied by yr.no.

File

src/Service/ParserService.php, line 251

Class

ParserService
Parsing of XML weather forecasts from yr.no.

Namespace

Drupal\weather\Service

Code

protected function updatePlaces($fc) {

  // Extract GeoID and latitude/longitude of returned XML data.
  // This might differ from the data we have in the database. An example
  // was Heraklion (ID 261745), which got the forecast for
  // Nomós Irakleíou (ID 261741).
  // Data to extract are:
  // geoid, latitude, longitude, country, name.
  $place['geoid'] = $fc->location->location['geobase'] . "_" . $fc->location->location['geobaseid'];
  $place['latitude'] = (string) $fc->location->location['latitude'];
  $place['latitude'] = round($place['latitude'], 5);
  $place['longitude'] = (string) $fc->location->location['longitude'];
  $place['longitude'] = round($place['longitude'], 5);
  $place['country'] = (string) $fc->location->country;
  $place['name'] = (string) $fc->location->name;
  $url = (string) $fc->credit->link['url'];
  [
    $country,
    $link,
  ] = $this->weatherHelper
    ->parsePlaceUrl($url);
  $place['link'] = $link;

  // Fetch stored information about geoid.
  $existingPlace = $this->weatherPlaceStorage
    ->load($place['geoid']);

  // If the geoid is not in the database, add it.
  if (!$existingPlace) {
    $place['status'] = 'added';
    $this->weatherPlaceStorage
      ->create($place)
      ->save();
  }
  else {

    // Compare the stored information with the downloaded information.
    // If they differ, update the database.
    $modified = FALSE;
    foreach ($place as $field => $value) {
      $existingValue = $existingPlace->{$field}->value;
      if ($existingPlace
        ->hasField($field) && $existingValue != $value) {
        $existingPlace->{$field} = $value;
        $modified = TRUE;
      }
    }
    if ($modified) {
      $existingPlace->status = WeatherPlaceInterface::STATUS_MODIFIED;
      $existingPlace
        ->save();
    }
  }
}