You are here

public function WeatherHourlyBlock::build in Wunderground weather 8

Builds and returns the renderable array for this block plugin.

If a block should not be rendered because it has no content, then this method must also ensure to return no content: it must then only return an empty array, or an empty array with #cache set (with cacheability metadata indicating the circumstances for it being empty).

Return value

array A renderable array representing the content of the block.

Overrides BlockPluginInterface::build

See also

\Drupal\block\BlockViewBuilder

File

src/Plugin/Block/WeatherHourlyBlock.php, line 173
Contains \Drupal\wunderground_weather\Plugin\Block\WeatherHourlyBlock.

Class

WeatherHourlyBlock
Provides a with an hourly weather forecast.

Namespace

Drupal\wunderground_weather\Plugin\Block

Code

public function build() {

  // Get block configuration.
  $config = $this
    ->getConfiguration();
  $location = $config['location'];
  $used_fields = $config['used_fields'];
  $available_fields = $this
    ->getAvailableFields();

  // Get all settings.
  $settings = $this->wundergroundWeatherManager
    ->getSettings();
  preg_match('#\\[(.*?)\\]#', $location, $match);
  $path = $match[1];
  $options = [
    'api' => 'api',
    'key' => $settings
      ->get('api_key'),
    'data_feature' => 'hourly',
    'language' => 'lang:' . strtoupper($settings
      ->get('language')),
    'path' => $path,
  ];
  $data = $this->wundergroundWeatherManager
    ->requestData($options);
  $rows = [];
  $hours = isset($data->hourly_forecast) ? $data->hourly_forecast : [];
  if ($hours) {
    foreach ($hours as $i => $hour) {
      if ($i >= $config['number_of_hours']) {
        break;
      }
      $row['data']['hour'] = $hour->FCTTIME->hour . ':' . $hour->FCTTIME->min;
      foreach ($used_fields as $field) {
        if ($field) {
          $row['data'][$field] = call_user_func([
            $this,
            'get' . ucfirst($field),
          ], $hour);
        }
      }
      $rows[] = $row;
    }
  }
  $header[] = t('Hours');
  foreach ($used_fields as $used_field) {
    if ($used_field) {
      $header[] = $available_fields[$used_field];
    }
  }
  return [
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $rows,
  ];
}