You are here

protected function ThemeService::formatTemperature in Weather 8

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

Converts temperatures.

Parameters

int $temperature: Temperature in degree celsius.

string $unit: Unit to be returned (celsius, fahrenheit, ...).

Return value

array Formatted representation in the desired unit.

2 calls to ThemeService::formatTemperature()
ThemeService::formatWindchillTemperature in src/Service/ThemeService.php
Calculates windchill temperature.
ThemeService::setForecastsVariables in src/Service/ThemeService.php
Adds variables related to weather forecast.

File

src/Service/ThemeService.php, line 289

Class

ThemeService
ThemeService service.

Namespace

Drupal\weather\Service

Code

protected function formatTemperature($temperature, $unit) {

  // Do the calculation.
  $fahrenheit = (int) ($temperature * 9 / 5) + 32;

  // Format the temperature.
  if ($unit == 'fahrenheit') {
    $result = $this
      ->t('@temperature °F', [
      '@temperature' => $fahrenheit,
    ]);
  }
  elseif ($unit == 'celsiusfahrenheit') {
    $result = $this
      ->t('@temperature_c °C / @temperature_f °F', [
      '@temperature_c' => $temperature,
      '@temperature_f' => $fahrenheit,
    ]);
  }
  elseif ($unit == 'fahrenheitcelsius') {
    $result = $this
      ->t('@temperature_f °F / @temperature_c °C', [
      '@temperature_f' => $fahrenheit,
      '@temperature_c' => $temperature,
    ]);
  }
  elseif ($unit == 'celsius_value') {
    $result = $temperature;
  }
  elseif ($unit == 'fahrenheit_value') {
    $result = $fahrenheit;
  }
  else {

    // Default to metric units.
    $result = $this
      ->t('@temperature °C', [
      '@temperature' => $temperature,
    ]);
  }
  return [
    '#markup' => preg_replace("/([^ ]*)&thinsp;([^ ]*)/", '<span style="white-space:nowrap;">\\1&thinsp;\\2</span>', $result),
  ];
}