You are here

public function ParserTest::weatherUpdatePlaces in Weather 8

Same name and namespace in other branches
  1. 2.0.x tests/src/Functional/ParserTest.php \Drupal\Tests\weather\Functional\ParserTest::weatherUpdatePlaces()

Handle updates to the weather_places table.

1 call to ParserTest::weatherUpdatePlaces()
ParserTest::weatherParseForecast in tests/src/Functional/ParserTest.php
Parses an XML forecast supplied by yr.no.

File

tests/src/Functional/ParserTest.php, line 194

Class

ParserTest
Tests parsing of XML weather forecasts.

Namespace

Drupal\Tests\weather\Functional

Code

public function weatherUpdatePlaces($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'];

  // Remove "http://www.yr.no/place/" from the URL.
  // fixme: not reliable in case we have https;//... at the beginning.
  $link = substr($url, 23);

  // Split by slashes and remove country (first item)
  // and "forecast.xml" (last item)
  $link_parts = explode('/', $link);

  // Remove country.
  array_shift($link_parts);

  // Remove "forecast.xml".
  array_pop($link_parts);
  $place['link'] = implode('/', $link_parts);

  // Fetch stored information about geoid.
  $info = $this
    ->weatherGetInformationAboutGeoid($place['geoid']);

  // If the geoid is not in the database, add it.
  if ($info === FALSE) {
    $place['status'] = 'added';

    // Insert the record to table.
    \Drupal::database()
      ->insert('weather_place')
      ->fields($place)
      ->execute();
  }
  else {

    // Compare the stored information with the downloaded information.
    // If they differ, update the database.
    $stored_info = (array) $info;
    unset($stored_info['status']);
    $diff = array_diff_assoc($stored_info, $place);
    if (!empty($diff)) {
      $place['status'] = WeatherPlaceInterface::STATUS_MODIFIED;
      \Drupal::database()
        ->update('weather_place')
        ->condition('geoid', $place['geoid'])
        ->updateFields($place)
        ->execute();
    }
  }
}