You are here

protected function ThemeService::calculateSunInfo in Weather 8

Same name and namespace in other branches
  1. 2.0.x src/Service/ThemeService.php \Drupal\weather\Service\ThemeService::calculateSunInfo()

Calculate the times of sunrise and sunset.

Parameters

string $date: The date for which the calculation should be made.

int $utc_offset: UTC offset of local time in minutes.

string $geoid: The GeoID of a place.

Return value

array|string An array with sunrise and sunset times in the local timezone. If a string is returned, this is the special case for polar day or polar night without sunrise and sunset.

1 call to ThemeService::calculateSunInfo()
ThemeService::setForecastsVariables in src/Service/ThemeService.php
Adds variables related to weather forecast.

File

src/Service/ThemeService.php, line 212

Class

ThemeService
ThemeService service.

Namespace

Drupal\weather\Service

Code

protected function calculateSunInfo($date, $utc_offset, $geoid) {

  // Get the coordinates for sunrise and sunset calculation.
  $weatherPlace = $this->weatherPlaceStorage
    ->load($geoid);

  // Calculate the timestamp for the local time zone.
  $time = strtotime($date . ' 12:00:00 UTC') - 60 * $utc_offset;
  $sun_info = date_sun_info($time, $weatherPlace->latitude->value, $weatherPlace->longitude->value);

  // Handle special cases (no sunrise or sunset at all).
  if ($sun_info['sunrise'] == 0 and $sun_info['sunset'] == 0) {

    // Sun is always below the horizon.
    $result = $this
      ->t('No sunrise, polar night');
  }
  elseif ($sun_info['sunrise'] == 1 and $sun_info['sunset'] == 1) {

    // Sun is always above the horizon.
    $result = $this
      ->t('No sunset, polar day');
  }
  else {

    // There is a sunrise and a sunset.
    // We don't need the exact second of the sunrise and sunset.
    // Therefore, the times are rounded to the next minute.
    $time = round($sun_info['sunrise'] / 60) * 60;
    $time = gmdate('H:i', $time + 60 * $utc_offset);
    $result['sunrise'] = $time;
    $time = round($sun_info['sunset'] / 60) * 60;
    $time = gmdate('H:i', $time + 60 * $utc_offset);
    $result['sunset'] = $time;
  }
  return $result;
}