You are here

public function InstagramBlockBlock::build in Instagram Block 8

Same name and namespace in other branches
  1. 8.3 src/Plugin/Block/InstagramBlockBlock.php \Drupal\instagram_block\Plugin\Block\InstagramBlockBlock::build()
  2. 8.2 src/Plugin/Block/InstagramBlockBlock.php \Drupal\instagram_block\Plugin\Block\InstagramBlockBlock::build()

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/InstagramBlockBlock.php, line 166
Contains \Drupal\instagram_block\Plugin\Block\InstagramBlockBlock.

Class

InstagramBlockBlock
Provides an Instagram block.

Namespace

Drupal\instagram_block\Plugin\Block

Code

public function build() {

  // Build a render array to return the Instagram Images.
  $build = array();
  $module_config = $this->configFactory
    ->get('instagram_block.settings')
    ->get();

  // If no configuration was saved, don't attempt to build block.
  if (empty($module_config['user_id']) || empty($module_config['access_token'])) {

    // @TODO Display a message instructing user to configure module.
    return $build;
  }

  // Build url for http request.
  $uri = "https://api.instagram.com/v1/users/{$module_config['user_id']}/media/recent/";
  $options = [
    'query' => [
      'access_token' => $module_config['access_token'],
      'count' => $this->configuration['count'],
    ],
  ];
  $url = Url::fromUri($uri, $options)
    ->toString();

  // Get the instagram images and decode.
  $result = $this
    ->_fetchData($url);
  if (!$result) {
    return $build;
  }
  foreach ($result['data'] as $post) {
    $build['children'][$post['id']] = array(
      '#theme' => 'instagram_block_image',
      '#data' => $post,
      '#href' => $post['link'],
      '#src' => $post['images'][$this->configuration['img_resolution']]['url'],
      '#width' => $this->configuration['width'],
      '#height' => $this->configuration['height'],
    );
  }

  // Add css.
  if (!empty($build)) {
    $build['#attached']['library'][] = 'instagram_block/instagram_block';
  }

  // Cache for a day.
  $build['#cache']['keys'] = [
    'instagram_block',
    'block',
  ];
  $build['#cache']['max_age'] = $this->configuration['cache_time_minutes'] * 60;
  return $build;
}