You are here

public function InstagramBlockBlock::build in Instagram Block 8.2

Same name and namespace in other branches
  1. 8.3 src/Plugin/Block/InstagramBlockBlock.php \Drupal\instagram_block\Plugin\Block\InstagramBlockBlock::build()
  2. 8 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 177

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 = [];

  // If no configuration was saved, don't attempt to build block.
  if (empty($this->configuration['access_token'])) {
    $this->loggerFactory
      ->get('instagram_block')
      ->error($this
      ->t('No access_token set'));
    return $build;
  }

  // Build url for http request.
  $uri = "https://api.instagram.com/v1/users/self/media/recent/";
  $options = [
    'query' => [
      'access_token' => $this->configuration['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']] = [
      '#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'] = [
    'block',
    'instagram_block',
    $this->configuration['id'],
    $this->configuration['access_token'],
  ];
  $build['#cache']['context'][] = 'languages:language_content';
  $build['#cache']['max-age'] = $this->configuration['cache_time_minutes'] * 60;
  return $build;
}