You are here

public function Blocks::preRenderBlock in Context 8.4

Same name and namespace in other branches
  1. 8 src/Plugin/ContextReaction/Blocks.php \Drupal\context\Plugin\ContextReaction\Blocks::preRenderBlock()
  2. 8.0 src/Plugin/ContextReaction/Blocks.php \Drupal\context\Plugin\ContextReaction\Blocks::preRenderBlock()

Renders the content using the provided block plugin.

Parameters

array $build: The block to be rendered.

Return value

array The block already rendered.

File

src/Plugin/ContextReaction/Blocks.php, line 337

Class

Blocks
Provides a content reaction.

Namespace

Drupal\context\Plugin\ContextReaction

Code

public function preRenderBlock(array $build) {
  $content = $build['#block_plugin']
    ->build();
  unset($build['#block_plugin']);

  // Abort rendering: render as the empty string and ensure this block is
  // render cached, so we can avoid the work of having to repeatedly
  // determine whether the block is empty. E.g. modifying or adding entities
  // could cause the block to no longer be empty.
  if (is_null($content) || Element::isEmpty($content)) {
    $build = [
      '#markup' => '',
      '#cache' => $build['#cache'],
    ];

    // If $content is not empty, then it contains cacheability metadata, and
    // we must merge it with the existing cacheability metadata. This allows
    // blocks to be empty, yet still bubble cacheability metadata, to indicate
    // why they are empty.
    if (!empty($content)) {
      CacheableMetadata::createFromRenderArray($build)
        ->merge(CacheableMetadata::createFromRenderArray($content))
        ->applyTo($build);
    }
  }
  else {
    foreach ([
      '#attributes',
      '#contextual_links',
    ] as $property) {
      if (isset($content[$property])) {
        $build[$property] += $content[$property];
        unset($content[$property]);
      }
    }
    $block_configuration = $build['#configuration'];

    // Merge attributes from context.
    // @see #3150394 and #2979536.
    $existing_attributes = isset($build['#attributes']) ? $build['#attributes'] : [];

    // Merge existing attributes from block with class(es) configured
    // in Context.
    if (isset($block_configuration['css_class']) && '' !== $block_configuration['css_class']) {
      $new_attributes = [
        'class' => [
          $block_configuration['css_class'],
        ],
      ];
      $existing_attributes = array_merge_recursive($existing_attributes, $new_attributes);
    }
    $build['#attributes'] = $existing_attributes;
    $build['content'] = $content;
  }
  return $build;
}