function BlockViewBuilderTest::testBlockViewBuilderViewAlter

Same name and namespace in other branches
  1. 9 core/modules/block/tests/src/Kernel/BlockViewBuilderTest.php \Drupal\Tests\block\Kernel\BlockViewBuilderTest::testBlockViewBuilderViewAlter()
  2. 8.9.x core/modules/block/tests/src/Kernel/BlockViewBuilderTest.php \Drupal\Tests\block\Kernel\BlockViewBuilderTest::testBlockViewBuilderViewAlter()
  3. 11.x core/modules/block/tests/src/Kernel/BlockViewBuilderTest.php \Drupal\Tests\block\Kernel\BlockViewBuilderTest::testBlockViewBuilderViewAlter()

Tests block view altering.

See also

hook_block_view_alter()

hook_block_view_BASE_BLOCK_ID_alter()

File

core/modules/block/tests/src/Kernel/BlockViewBuilderTest.php, line 192

Class

BlockViewBuilderTest
Tests the block view builder.

Namespace

Drupal\Tests\block\Kernel

Code

public function testBlockViewBuilderViewAlter() : void {
  // Establish baseline.
  $build = $this->getBlockRenderArray();
  $this->setRawContent((string) $this->renderer
    ->renderRoot($build));
  $this->assertSame('Llamas > unicorns!', trim((string) $this->cssSelect('div')[0]));
  // Enable the block view alter hook that adds a foo=bar attribute.
  \Drupal::state()->set('block_test_view_alter_suffix', TRUE);
  Cache::invalidateTags($this->block
    ->getCacheTagsToInvalidate());
  $build = $this->getBlockRenderArray();
  $this->setRawContent((string) $this->renderer
    ->renderRoot($build));
  $this->assertSame('Llamas > unicorns!', trim((string) $this->cssSelect('[foo=bar]')[0]));
  \Drupal::state()->set('block_test_view_alter_suffix', FALSE);
  \Drupal::keyValue('block_test')->set('content', NULL);
  Cache::invalidateTags($this->block
    ->getCacheTagsToInvalidate());
  // Advanced: cached block, but an alter hook adds a #pre_render callback to
  // alter the eventual content.
  \Drupal::state()->set('block_test_view_alter_append_pre_render_prefix', TRUE);
  $build = $this->getBlockRenderArray();
  $this->assertFalse(isset($build['#prefix']), 'The appended #pre_render callback has not yet run before rendering.');
  $this->assertSame('Hiya!<br>', (string) $this->renderer
    ->renderRoot($build));
  // Check that a cached block without content is altered.
  $this->assertArrayHasKey('#prefix', $build);
  $this->assertSame('Hiya!<br>', $build['#prefix']);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.