You are here

public function WeatherForecastBlock::build in Wunderground weather 8

@todo use render array instead of theme function.

Overrides BlockPluginInterface::build

File

src/Plugin/Block/WeatherForecastBlock.php, line 179
Contains \Drupal\wunderground_weather\Plugin\Block\WeatherForecastBlock.

Class

WeatherForecastBlock
Provides a with a five day weather forecast.

Namespace

Drupal\wunderground_weather\Plugin\Block

Code

public function build() {

  // Get block configuration.
  $config = $this
    ->getConfiguration();
  $location = $config['location_forecast'];
  $number_of_days = $config['number_of_days'];
  $icon_set = $config['icon_set'];

  // Get all settings.
  $settings = $this->wundergroundWeatherManager
    ->getSettings();
  preg_match('#\\[(.*?)\\]#', $location, $match);
  $path = $match[1];
  $options = [
    'api' => 'api',
    'key' => $settings
      ->get('api_key'),
    'data_feature' => 'forecast10day',
    'language' => 'lang:' . strtoupper($settings
      ->get('language')),
    'path' => $path,
  ];
  $data = $this->wundergroundWeatherManager
    ->requestData($options);
  $days = isset($data->forecast) ? $data->forecast->simpleforecast->forecastday : [];
  $variables['#theme'] = 'wunderground_weather_forecast';
  $variables['#icon_set'] = $icon_set;
  $variables['#data'] = array_slice($days, 0, $number_of_days);
  $variables['#fields'] = $config['forecast_fields'];
  $variables['#temperature_scale'] = $config['temperature_scale'];
  $variables['#windspeed_scale'] = $config['windspeed_scale'];

  // Check if data is received.
  if ($data) {
    $output = render($variables);
  }
  else {

    // Return message if no data is retrieved.
    $output = t('No weather forecast available.');
  }
  return [
    '#children' => $output,
  ];
}