You are here

protected function ParserService::downloadWeather in Weather 2.0.x

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

Downloads forecast from yr.no and puts it do DB.

1 call to ParserService::downloadWeather()
ParserService::getWeather in src/Service/ParserService.php
Returns a weather object for the specified GeoID.

File

src/Service/ParserService.php, line 442

Class

ParserService
Parsing of XML weather forecasts from yr.no.

Namespace

Drupal\weather\Service

Code

protected function downloadWeather(string $geoid, int $time) : array {
  $currentUtcTime = gmdate('Y-m-d H:i:s');
  $meta = [
    'geoid' => $geoid,
    'last_update' => $currentUtcTime,
    'next_update' => $currentUtcTime,
    'next_download_attempt' => $currentUtcTime,
    'utc_offset' => 0,
  ];

  // Get the scheduled time of next update. If there is no entry for
  // the specified GeoID, $meta will have default values.
  $forecastInfo = $this->weatherForecastInfoStorage
    ->load($geoid);
  if ($forecastInfo instanceof WeatherForecastInformationInterface) {

    // Update $meta with DB record.
    foreach ($meta as $key => $value) {
      if ($key != 'geoid' && $forecastInfo
        ->hasField($key) && !$forecastInfo->{$key}
        ->isEmpty()) {
        $meta[$key] = $forecastInfo->{$key}->value;
      }
    }
  }

  // If the next scheduled download is due, try to get forecasts.
  if ($currentUtcTime >= $meta['next_download_attempt']) {
    $result = $this
      ->downloadForecast($geoid);
    if (!$result) {
      $this
        ->setNextAttempt($meta, $time);
    }
    else {

      // If that worked, get the next scheduled update time.
      $forecastInfo = $this->weatherForecastInfoStorage
        ->load($geoid);

      // If the download did succeed, but
      // the returned forecast is old and the next update is overdue.
      // In that case, the download attempt needs to wait as well,
      // otherwise, a new download will occur on every page load.
      $newNextUpdate = $forecastInfo->next_update->value;
      if ($currentUtcTime >= $newNextUpdate) {

        // Update $meta with DB record.
        foreach ($meta as $key => $value) {
          if ($key != 'geoid' && $forecastInfo
            ->hasField($key) && !$forecastInfo->{$key}
            ->isEmpty()) {
            $meta[$key] = $forecastInfo->{$key}->value;
          }
        }
        $this
          ->setNextAttempt($meta, $time);
      }
    }
  }
  return $meta;
}