You are here

public function InstagramPostBlock::build in Social Feed 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/InstagramPostBlock.php, line 159

Class

InstagramPostBlock
Provides a 'InstagramPostBlock' block.

Namespace

Drupal\socialfeed\Plugin\Block

Code

public function build() {
  $build = [];
  $items = [];

  // Refresh the long-lived Access Token.
  $this
    ->refreshAccessToken();
  $instagram = $this->instagram
    ->createInstance($this
    ->getSetting('client_id'), $this
    ->getSetting('app_secret'), $this
    ->getSetting('redirect_uri'), $this
    ->getSetting('access_token'));
  $posts = $instagram
    ->getPosts($this
    ->getSetting('picture_count'));

  // Validating the settings.
  $post_link = $this
    ->getSetting('post_link');
  $video_thumbnail = $this
    ->getSetting('video_thumbnail');
  foreach ($posts as $post) {
    $theme_type = $post['raw']->media_type == 'VIDEO' ? 'video' : ($post['raw']->media_type == 'CAROUSEL_ALBUM' ? 'carousel_album' : 'image');

    // Set the post link.
    if ($post_link) {
      $post['post_url'] = $post['raw']->permalink;
    }

    // Use video thumbnails instead of rendered videos.
    if ($video_thumbnail && $theme_type == 'video') {
      $theme_type = 'image';
      $post['media_url'] = $post['raw']->thumbnail_url;
    }
    $items[] = [
      '#theme' => 'socialfeed_instagram_post_' . $theme_type,
      '#post' => $post,
      '#cache' => [
        // Cache for 1 hour.
        'max-age' => 60 * 60,
        'cache tags' => $this->config
          ->getCacheTags(),
        'context' => $this->config
          ->getCacheContexts(),
      ],
    ];
  }
  $build['posts'] = [
    '#theme' => 'item_list',
    '#items' => $items,
  ];
  return $build;
}