You are here

public function SocialMediaLinksBlock::build in Social Media Links Block and Field 8.2

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/SocialMediaLinksBlock.php, line 356

Class

SocialMediaLinksBlock
Provides the Social Media Links Block.

Namespace

Drupal\social_media_links\Plugin\Block

Code

public function build() {
  $config = $this
    ->getConfiguration();
  $platforms = $this->platformManager
    ->getPlatformsWithValue($config['platforms']);
  if (count($platforms) < 1) {
    return [];
  }
  $iconset = IconsetBase::explodeStyle($config['iconset']['style']);
  try {
    $iconsetInstance = $this->iconsetManager
      ->createInstance($iconset['iconset']);
  } catch (PluginException $exception) {
    $this->logger
      ->error('The selected "@iconset" iconset plugin does not exist.', [
      '@iconset' => $iconset['iconset'],
    ]);
    return [];
  }
  foreach ($config['link_attributes'] as $key => $value) {
    if ($value === '<none>') {
      unset($config['link_attributes'][$key]);
    }
  }

  // Set the attributes for the individual links.
  //
  // We use two different types of link attributes:
  // * "global" attributes that affects all links (e.g. target or rel)
  // which are set in $config['link_attributes'];
  // * "individual" attributes for each link (e.g. title) which are defined
  // in $platforms[$platform_id]['attributes'].
  foreach ($platforms as $platform_id => $platform) {
    $platforms[$platform_id]['element'] = (array) $iconsetInstance
      ->getIconElement($platform['instance'], $iconset['style']);
    $platforms[$platform_id]['attributes'] = new Attribute($config['link_attributes']);
    if (!empty($platform['instance']
      ->getDescription())) {
      $platforms[$platform_id]['attributes']
        ->setAttribute('aria-label', $platform['instance']
        ->getDescription());
      $platforms[$platform_id]['attributes']
        ->setAttribute('title', $platform['instance']
        ->getDescription());
    }
  }
  $output = [
    '#theme' => 'social_media_links_platforms',
    '#platforms' => $platforms,
    '#appearance' => $config['appearance'],
    '#attached' => [
      'library' => [
        'social_media_links/social_media_links.theme',
      ],
    ],
  ];
  if ($iconsetInstance
    ->getPath() === 'library' && (array) ($library = $iconsetInstance
    ->getLibrary())) {
    $output['#attached']['library'] = array_merge_recursive($output['#attached']['library'], $library);
  }
  return [
    $output,
  ];
}