Chris@0: controller = $this->container
Chris@0: ->get('entity_type.manager')
Chris@0: ->getStorage('block');
Chris@0:
Chris@0: \Drupal::state()->set('block_test.content', 'Llamas > unicorns!');
Chris@0:
Chris@0: // Create a block with only required values.
Chris@0: $this->block = $this->controller->create([
Chris@0: 'id' => 'test_block',
Chris@0: 'theme' => 'stark',
Chris@0: 'plugin' => 'test_cache',
Chris@0: ]);
Chris@0: $this->block->save();
Chris@0:
Chris@0: $this->container->get('cache.render')->deleteAll();
Chris@0:
Chris@0: $this->renderer = $this->container->get('renderer');
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Tests the rendering of blocks.
Chris@0: */
Chris@0: public function testBasicRendering() {
Chris@0: \Drupal::state()->set('block_test.content', '');
Chris@0:
Chris@0: $entity = $this->controller->create([
Chris@0: 'id' => 'test_block1',
Chris@0: 'theme' => 'stark',
Chris@0: 'plugin' => 'test_html',
Chris@0: ]);
Chris@0: $entity->save();
Chris@0:
Chris@0: // Test the rendering of a block.
Chris@0: $entity = Block::load('test_block1');
Chris@0: $output = entity_view($entity, 'block');
Chris@0: $expected = [];
Chris@0: $expected[] = '
';
Chris@0: $expected[] = ' ';
Chris@0: $expected[] = ' ';
Chris@0: $expected[] = ' ';
Chris@0: $expected[] = '
';
Chris@0: $expected[] = '';
Chris@0: $expected_output = implode("\n", $expected);
Chris@0: $this->assertEqual($this->renderer->renderRoot($output), $expected_output);
Chris@0:
Chris@0: // Reset the HTML IDs so that the next render is not affected.
Chris@0: Html::resetSeenIds();
Chris@0:
Chris@0: // Test the rendering of a block with a given title.
Chris@0: $entity = $this->controller->create([
Chris@0: 'id' => 'test_block2',
Chris@0: 'theme' => 'stark',
Chris@0: 'plugin' => 'test_html',
Chris@0: 'settings' => [
Chris@0: 'label' => 'Powered by Bananas',
Chris@0: ],
Chris@0: ]);
Chris@0: $entity->save();
Chris@0: $output = entity_view($entity, 'block');
Chris@0: $expected = [];
Chris@0: $expected[] = '';
Chris@0: $expected[] = ' ';
Chris@0: $expected[] = '
Powered by Bananas
';
Chris@0: $expected[] = ' ';
Chris@0: $expected[] = ' ';
Chris@0: $expected[] = ' ';
Chris@0: $expected[] = '';
Chris@0: $expected_output = implode("\n", $expected);
Chris@0: $this->assertEqual($this->renderer->renderRoot($output), $expected_output);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Tests block render cache handling.
Chris@0: */
Chris@0: public function testBlockViewBuilderCache() {
Chris@0: // Verify cache handling for a non-empty block.
Chris@0: $this->verifyRenderCacheHandling();
Chris@0:
Chris@0: // Create an empty block.
Chris@0: $this->block = $this->controller->create([
Chris@0: 'id' => 'test_block',
Chris@0: 'theme' => 'stark',
Chris@0: 'plugin' => 'test_cache',
Chris@0: ]);
Chris@0: $this->block->save();
Chris@0: \Drupal::state()->set('block_test.content', NULL);
Chris@0:
Chris@0: // Verify cache handling for an empty block.
Chris@0: $this->verifyRenderCacheHandling();
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Verifies render cache handling of the block being tested.
Chris@0: *
Chris@0: * @see ::testBlockViewBuilderCache()
Chris@0: */
Chris@0: protected function verifyRenderCacheHandling() {
Chris@0: // Force a request via GET so we can test the render cache.
Chris@0: $request = \Drupal::request();
Chris@0: $request_method = $request->server->get('REQUEST_METHOD');
Chris@0: $request->setMethod('GET');
Chris@0:
Chris@0: // Test that a cache entry is created.
Chris@0: $build = $this->getBlockRenderArray();
Chris@0: $cid = 'entity_view:block:test_block:' . implode(':', \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions'])->getKeys());
Chris@0: $this->renderer->renderRoot($build);
Chris@0: $this->assertTrue($this->container->get('cache.render')->get($cid), 'The block render element has been cached.');
Chris@0:
Chris@0: // Re-save the block and check that the cache entry has been deleted.
Chris@0: $this->block->save();
Chris@0: $this->assertFalse($this->container->get('cache.render')->get($cid), 'The block render cache entry has been cleared when the block was saved.');
Chris@0:
Chris@0: // Rebuild the render array (creating a new cache entry in the process) and
Chris@0: // delete the block to check the cache entry is deleted.
Chris@0: unset($build['#printed']);
Chris@0: // Re-add the block because \Drupal\block\BlockViewBuilder::buildBlock()
Chris@0: // removes it.
Chris@0: $build['#block'] = $this->block;
Chris@0:
Chris@0: $this->renderer->renderRoot($build);
Chris@0: $this->assertTrue($this->container->get('cache.render')->get($cid), 'The block render element has been cached.');
Chris@0: $this->block->delete();
Chris@0: $this->assertFalse($this->container->get('cache.render')->get($cid), 'The block render cache entry has been cleared when the block was deleted.');
Chris@0:
Chris@0: // Restore the previous request method.
Chris@0: $request->setMethod($request_method);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Tests block view altering.
Chris@0: *
Chris@0: * @see hook_block_view_alter()
Chris@0: * @see hook_block_view_BASE_BLOCK_ID_alter()
Chris@0: */
Chris@0: public function testBlockViewBuilderViewAlter() {
Chris@0: // Establish baseline.
Chris@0: $build = $this->getBlockRenderArray();
Chris@0: $this->setRawContent((string) $this->renderer->renderRoot($build));
Chris@0: $this->assertIdentical(trim((string) $this->cssSelect('div')[0]), 'Llamas > unicorns!');
Chris@0:
Chris@0: // Enable the block view alter hook that adds a foo=bar attribute.
Chris@0: \Drupal::state()->set('block_test_view_alter_suffix', TRUE);
Chris@0: Cache::invalidateTags($this->block->getCacheTagsToInvalidate());
Chris@0: $build = $this->getBlockRenderArray();
Chris@0: $this->setRawContent((string) $this->renderer->renderRoot($build));
Chris@0: $this->assertIdentical(trim((string) $this->cssSelect('[foo=bar]')[0]), 'Llamas > unicorns!');
Chris@0: \Drupal::state()->set('block_test_view_alter_suffix', FALSE);
Chris@0:
Chris@0: \Drupal::state()->set('block_test.content', NULL);
Chris@0: Cache::invalidateTags($this->block->getCacheTagsToInvalidate());
Chris@0:
Chris@0: // Advanced: cached block, but an alter hook adds a #pre_render callback to
Chris@0: // alter the eventual content.
Chris@0: \Drupal::state()->set('block_test_view_alter_append_pre_render_prefix', TRUE);
Chris@0: $build = $this->getBlockRenderArray();
Chris@0: $this->assertFalse(isset($build['#prefix']), 'The appended #pre_render callback has not yet run before rendering.');
Chris@0: $this->assertIdentical((string) $this->renderer->renderRoot($build), 'Hiya!
');
Chris@0: $this->assertTrue(isset($build['#prefix']) && $build['#prefix'] === 'Hiya!
', 'A cached block without content is altered.');
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Tests block build altering.
Chris@0: *
Chris@0: * @see hook_block_build_alter()
Chris@0: * @see hook_block_build_BASE_BLOCK_ID_alter()
Chris@0: */
Chris@0: public function testBlockViewBuilderBuildAlter() {
Chris@0: // Force a request via GET so we can test the render cache.
Chris@0: $request = \Drupal::request();
Chris@0: $request_method = $request->server->get('REQUEST_METHOD');
Chris@0: $request->setMethod('GET');
Chris@0:
Chris@0: $default_keys = ['entity_view', 'block', 'test_block'];
Chris@0: $default_contexts = [];
Chris@0: $default_tags = ['block_view', 'config:block.block.test_block'];
Chris@0: $default_max_age = Cache::PERMANENT;
Chris@0:
Chris@0: // hook_block_build_alter() adds an additional cache key.
Chris@0: $alter_add_key = $this->randomMachineName();
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_key', $alter_add_key);
Chris@0: $this->assertBlockRenderedWithExpectedCacheability(array_merge($default_keys, [$alter_add_key]), $default_contexts, $default_tags, $default_max_age);
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_key', NULL);
Chris@0:
Chris@0: // hook_block_build_alter() adds an additional cache context.
Chris@0: $alter_add_context = 'url.query_args:' . $this->randomMachineName();
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_context', $alter_add_context);
Chris@0: $this->assertBlockRenderedWithExpectedCacheability($default_keys, Cache::mergeContexts($default_contexts, [$alter_add_context]), $default_tags, $default_max_age);
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_context', NULL);
Chris@0:
Chris@0: // hook_block_build_alter() adds an additional cache tag.
Chris@0: $alter_add_tag = $this->randomMachineName();
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_tag', $alter_add_tag);
Chris@0: $this->assertBlockRenderedWithExpectedCacheability($default_keys, $default_contexts, Cache::mergeTags($default_tags, [$alter_add_tag]), $default_max_age);
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_tag', NULL);
Chris@0:
Chris@0: // hook_block_build_alter() alters the max-age.
Chris@0: $alter_max_age = 300;
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_max_age', $alter_max_age);
Chris@0: $this->assertBlockRenderedWithExpectedCacheability($default_keys, $default_contexts, $default_tags, $alter_max_age);
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_max_age', NULL);
Chris@0:
Chris@0: // hook_block_build_alter() alters cache keys, contexts, tags and max-age.
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_key', $alter_add_key);
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_context', $alter_add_context);
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_tag', $alter_add_tag);
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_max_age', $alter_max_age);
Chris@0: $this->assertBlockRenderedWithExpectedCacheability(array_merge($default_keys, [$alter_add_key]), Cache::mergeContexts($default_contexts, [$alter_add_context]), Cache::mergeTags($default_tags, [$alter_add_tag]), $alter_max_age);
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_key', NULL);
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_context', NULL);
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_tag', NULL);
Chris@0: \Drupal::state()->set('block_test_block_alter_cache_max_age', NULL);
Chris@0:
Chris@0: // hook_block_build_alter() sets #create_placeholder.
Chris@0: foreach ([TRUE, FALSE] as $value) {
Chris@0: \Drupal::state()->set('block_test_block_alter_create_placeholder', $value);
Chris@0: $build = $this->getBlockRenderArray();
Chris@0: $this->assertTrue(isset($build['#create_placeholder']));
Chris@0: $this->assertIdentical($value, $build['#create_placeholder']);
Chris@0: }
Chris@0: \Drupal::state()->set('block_test_block_alter_create_placeholder', NULL);
Chris@0:
Chris@0: // Restore the previous request method.
Chris@0: $request->setMethod($request_method);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Asserts that a block is built/rendered/cached with expected cacheability.
Chris@0: *
Chris@0: * @param string[] $expected_keys
Chris@0: * The expected cache keys.
Chris@0: * @param string[] $expected_contexts
Chris@0: * The expected cache contexts.
Chris@0: * @param string[] $expected_tags
Chris@0: * The expected cache tags.
Chris@0: * @param int $expected_max_age
Chris@0: * The expected max-age.
Chris@0: */
Chris@0: protected function assertBlockRenderedWithExpectedCacheability(array $expected_keys, array $expected_contexts, array $expected_tags, $expected_max_age) {
Chris@0: $required_cache_contexts = ['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions'];
Chris@0:
Chris@0: // Check that the expected cacheability metadata is present in:
Chris@0: // - the built render array;
Chris@0: $this->pass('Built render array');
Chris@0: $build = $this->getBlockRenderArray();
Chris@0: $this->assertIdentical($expected_keys, $build['#cache']['keys']);
Chris@0: $this->assertIdentical($expected_contexts, $build['#cache']['contexts']);
Chris@0: $this->assertIdentical($expected_tags, $build['#cache']['tags']);
Chris@0: $this->assertIdentical($expected_max_age, $build['#cache']['max-age']);
Chris@0: $this->assertFalse(isset($build['#create_placeholder']));
Chris@0: // - the rendered render array;
Chris@0: $this->pass('Rendered render array');
Chris@0: $this->renderer->renderRoot($build);
Chris@0: // - the render cache item.
Chris@0: $this->pass('Render cache item');
Chris@0: $final_cache_contexts = Cache::mergeContexts($expected_contexts, $required_cache_contexts);
Chris@0: $cid = implode(':', $expected_keys) . ':' . implode(':', \Drupal::service('cache_contexts_manager')->convertTokensToKeys($final_cache_contexts)->getKeys());
Chris@0: $cache_item = $this->container->get('cache.render')->get($cid);
Chris@0: $this->assertTrue($cache_item, 'The block render element has been cached with the expected cache ID.');
Chris@0: $this->assertIdentical(Cache::mergeTags($expected_tags, ['rendered']), $cache_item->tags);
Chris@0: $this->assertIdentical($final_cache_contexts, $cache_item->data['#cache']['contexts']);
Chris@0: $this->assertIdentical($expected_tags, $cache_item->data['#cache']['tags']);
Chris@0: $this->assertIdentical($expected_max_age, $cache_item->data['#cache']['max-age']);
Chris@0:
Chris@0: $this->container->get('cache.render')->delete($cid);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Get a fully built render array for a block.
Chris@0: *
Chris@0: * @return array
Chris@0: * The render array.
Chris@0: */
Chris@0: protected function getBlockRenderArray() {
Chris@0: return $this->container->get('entity_type.manager')->getViewBuilder('block')->view($this->block, 'block');
Chris@0: }
Chris@0:
Chris@0: }