BlockViewBuilderTest.php 12.7 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\block\Tests\BlockViewBuilderTest.
 */

namespace Drupal\block\Tests;

10
use Drupal\Component\Utility\Html;
11
use Drupal\Core\Cache\Cache;
12
use Drupal\Core\Cache\UrlCacheContext;
13
use Drupal\simpletest\KernelTestBase;
14
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\HttpFoundation\RequestStack;
16
use Drupal\block\Entity\Block;
17 18 19

/**
 * Tests the block view builder.
20 21
 *
 * @group block
22
 */
23
class BlockViewBuilderTest extends KernelTestBase {
24 25

  /**
26
   * Modules to install.
27 28 29 30 31 32 33 34 35 36 37 38 39
   *
   * @var array
   */
  public static $modules = array('block', 'block_test', 'system');

  /**
   * The block being tested.
   *
   * @var \Drupal\block\Entity\BlockInterface
   */
  protected $block;

  /**
40
   * The block storage.
41
   *
42
   * @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface
43 44 45 46 47 48
   */
  protected $controller;

  /**
   * {@inheritdoc}
   */
49
  protected function setUp() {
50 51 52 53
    parent::setUp();

    $this->controller = $this->container
      ->get('entity.manager')
54
      ->getStorage('block');
55 56 57 58 59 60 61 62 63 64 65

    \Drupal::state()->set('block_test.content', 'Llamas &gt; unicorns!');

    // Create a block with only required values.
    $this->block = $this->controller->create(array(
      'id' => 'test_block',
      'theme' => 'stark',
      'plugin' => 'test_cache',
    ));
    $this->block->save();

66
    $this->container->get('cache.render')->deleteAll();
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
  }

  /**
   * Tests the rendering of blocks.
   */
  public function testBasicRendering() {
    \Drupal::state()->set('block_test.content', '');

    $entity = $this->controller->create(array(
      'id' => 'test_block1',
      'theme' => 'stark',
      'plugin' => 'test_html',
    ));
    $entity->save();

    // Test the rendering of a block.
83
    $entity = Block::load('test_block1');
84 85
    $output = entity_view($entity, 'block');
    $expected = array();
86
    $expected[] = '<div id="block-test-block1" class="block block-block-test">';
87 88
    $expected[] = '  ';
    $expected[] = '    ';
89 90
    $expected[] = '      ';
    $expected[] = '  </div>';
91 92 93 94 95
    $expected[] = '';
    $expected_output = implode("\n", $expected);
    $this->assertEqual(drupal_render($output), $expected_output);

    // Reset the HTML IDs so that the next render is not affected.
96
    Html::resetSeenIds();
97 98 99 100 101 102 103 104 105 106 107 108 109

    // Test the rendering of a block with a given title.
    $entity = $this->controller->create(array(
      'id' => 'test_block2',
      'theme' => 'stark',
      'plugin' => 'test_html',
      'settings' => array(
        'label' => 'Powered by Bananas',
      ),
    ));
    $entity->save();
    $output = entity_view($entity, 'block');
    $expected = array();
110
    $expected[] = '<div id="block-test-block2" class="block block-block-test">';
111 112 113
    $expected[] = '  ';
    $expected[] = '      <h2>Powered by Bananas</h2>';
    $expected[] = '    ';
114 115
    $expected[] = '      ';
    $expected[] = '  </div>';
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    $expected[] = '';
    $expected_output = implode("\n", $expected);
    $this->assertEqual(drupal_render($output), $expected_output);
  }

  /**
   * Tests block render cache handling.
   */
  public function testBlockViewBuilderCache() {
    // Verify cache handling for a non-empty block.
    $this->verifyRenderCacheHandling();

    // Create an empty block.
    $this->block = $this->controller->create(array(
      'id' => 'test_block',
      'theme' => 'stark',
      'plugin' => 'test_cache',
    ));
    $this->block->save();
    \Drupal::state()->set('block_test.content', NULL);

    // Verify cache handling for an empty block.
    $this->verifyRenderCacheHandling();
  }

  /**
   * Verifies render cache handling of the block being tested.
   *
   * @see ::testBlockViewBuilderCache()
   */
  protected function verifyRenderCacheHandling() {
    // Force a request via GET so we can get drupal_render() cache working.
148 149 150
    $request = \Drupal::request();
    $request_method = $request->server->get('REQUEST_METHOD');
    $request->setMethod('GET');
151 152 153 154 155 156 157 158 159 160 161 162 163 164

    // Test that entities with caching disabled do not generate a cache entry.
    $build = $this->getBlockRenderArray();
    $this->assertTrue(isset($build['#cache']) && array_keys($build['#cache']) == array('tags'), 'The render array element of uncacheable blocks is not cached, but does have cache tags set.');

    // Enable block caching.
    $this->setBlockCacheConfig(array(
      'max_age' => 600,
    ));

    // Test that a cache entry is created.
    $build = $this->getBlockRenderArray();
    $cid = drupal_render_cid_create($build);
    drupal_render($build);
165
    $this->assertTrue($this->container->get('cache.render')->get($cid), 'The block render element has been cached.');
166 167 168

    // Re-save the block and check that the cache entry has been deleted.
    $this->block->save();
169
    $this->assertFalse($this->container->get('cache.render')->get($cid), 'The block render cache entry has been cleared when the block was saved.');
170 171 172 173

    // Rebuild the render array (creating a new cache entry in the process) and
    // delete the block to check the cache entry is deleted.
    unset($build['#printed']);
174 175 176 177
    // Re-add the block because \Drupal\block\BlockViewBuilder::buildBlock()
    // removes it.
    $build['#block'] = $this->block;

178
    drupal_render($build);
179
    $this->assertTrue($this->container->get('cache.render')->get($cid), 'The block render element has been cached.');
180
    $this->block->delete();
181
    $this->assertFalse($this->container->get('cache.render')->get($cid), 'The block render cache entry has been cleared when the block was deleted.');
182 183

    // Restore the previous request method.
184
    $request->setMethod($request_method);
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  }

  /**
   * Tests block view altering.
   */
  public function testBlockViewBuilderAlter() {
    // Establish baseline.
    $build = $this->getBlockRenderArray();
    $this->assertIdentical(drupal_render($build), 'Llamas &gt; unicorns!');

    // Enable the block view alter hook that adds a suffix, for basic testing.
    \Drupal::state()->set('block_test_view_alter_suffix', TRUE);

    // Basic: non-empty block.
    $build = $this->getBlockRenderArray();
    $this->assertTrue(isset($build['#suffix']) && $build['#suffix'] === '<br>Goodbye!', 'A block with content is altered.');
    $this->assertIdentical(drupal_render($build), 'Llamas &gt; unicorns!<br>Goodbye!');

    // Basic: empty block.
    \Drupal::state()->set('block_test.content', NULL);
    $build = $this->getBlockRenderArray();
    $this->assertTrue(isset($build['#suffix']) && $build['#suffix'] === '<br>Goodbye!', 'A block without content is altered.');
    $this->assertIdentical(drupal_render($build), '<br>Goodbye!');

    // Disable the block view alter hook that adds a suffix, for basic testing.
    \Drupal::state()->set('block_test_view_alter_suffix', FALSE);

    // Force a request via GET so we can get drupal_render() cache working.
213 214 215
    $request = \Drupal::request();
    $request_method = $request->server->get('REQUEST_METHOD');
    $request->setMethod('GET');
216 217

    $default_keys = array('entity_view', 'block', 'test_block', 'en', 'cache_context.theme');
218
    $default_tags = array('block_view', 'config:block.block.test_block', 'block_plugin:test_cache');
219 220 221 222 223

    // Advanced: cached block, but an alter hook adds an additional cache key.
    $this->setBlockCacheConfig(array(
      'max_age' => 600,
    ));
224
    $alter_add_key = $this->randomMachineName();
225 226 227 228 229 230
    \Drupal::state()->set('block_test_view_alter_cache_key', $alter_add_key);
    $expected_keys = array_merge($default_keys, array($alter_add_key));
    $build = $this->getBlockRenderArray();
    $this->assertIdentical($expected_keys, $build['#cache']['keys'], 'An altered cacheable block has the expected cache keys.');
    $cid = drupal_render_cid_create(array('#cache' => array('keys' => $expected_keys)));
    $this->assertIdentical(drupal_render($build), '');
231
    $cache_entry = $this->container->get('cache.render')->get($cid);
232
    $this->assertTrue($cache_entry, 'The block render element has been cached with the expected cache ID.');
233
    $expected_tags = array_merge($default_tags, ['rendered']);
234 235
    sort($expected_tags);
    $this->assertIdentical($cache_entry->tags, $expected_tags, 'The block render element has been cached with the expected cache tags.');
236
    $this->container->get('cache.render')->delete($cid);
237 238

    // Advanced: cached block, but an alter hook adds an additional cache tag.
239
    $alter_add_tag = $this->randomMachineName();
240
    \Drupal::state()->set('block_test_view_alter_cache_tag', $alter_add_tag);
241
    $expected_tags = Cache::mergeTags($default_tags, array($alter_add_tag));
242
    $build = $this->getBlockRenderArray();
243
    sort($build['#cache']['tags']);
244 245 246
    $this->assertIdentical($expected_tags, $build['#cache']['tags'], 'An altered cacheable block has the expected cache tags.');
    $cid = drupal_render_cid_create(array('#cache' => array('keys' => $expected_keys)));
    $this->assertIdentical(drupal_render($build), '');
247
    $cache_entry = $this->container->get('cache.render')->get($cid);
248
    $this->assertTrue($cache_entry, 'The block render element has been cached with the expected cache ID.');
249
    $expected_tags = array_merge($default_tags, [$alter_add_tag, 'rendered']);
250 251
    sort($expected_tags);
    $this->assertIdentical($cache_entry->tags, $expected_tags, 'The block render element has been cached with the expected cache tags.');
252
    $this->container->get('cache.render')->delete($cid);
253 254 255 256 257 258 259 260 261 262

    // 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 calling drupal_render().');
    $this->assertIdentical(drupal_render($build), 'Hiya!<br>');
    $this->assertTrue(isset($build['#prefix']) && $build['#prefix'] === 'Hiya!<br>', 'A cached block without content is altered.');

    // Restore the previous request method.
263
    $request->setMethod($request_method);
264 265 266 267 268 269 270 271 272 273 274 275
  }

  /**
   * Tests block render cache handling with configurable cache contexts.
   *
   * This is only intended to test that an existing block can be configured with
   * additional contexts, not to test that each context works correctly.
   *
   * @see \Drupal\block\Tests\BlockCacheTest
   */
  public function testBlockViewBuilderCacheContexts() {
    // Force a request via GET so we can get drupal_render() cache working.
276 277 278
    $request = \Drupal::request();
    $request_method = $request->server->get('REQUEST_METHOD');
    $request->setMethod('GET');
279 280 281 282 283 284 285 286

    // First: no cache context.
    $this->setBlockCacheConfig(array(
      'max_age' => 600,
    ));
    $build = $this->getBlockRenderArray();
    $cid = drupal_render_cid_create($build);
    drupal_render($build);
287
    $this->assertTrue($this->container->get('cache.render', $cid), 'The block render element has been cached.');
288 289 290 291 292 293 294 295 296 297

    // Second: the "per URL" cache context.
    $this->setBlockCacheConfig(array(
      'max_age' => 600,
      'contexts' => array('cache_context.url'),
    ));
    $old_cid = $cid;
    $build = $this->getBlockRenderArray();
    $cid = drupal_render_cid_create($build);
    drupal_render($build);
298
    $this->assertTrue($this->container->get('cache.render', $cid), 'The block render element has been cached.');
299 300 301 302
    $this->assertNotEqual($cid, $old_cid, 'The cache ID has changed.');

    // Third: the same block configuration, but a different URL.
    $original_url_cache_context = $this->container->get('cache_context.url');
303 304 305
    $request_stack = new RequestStack();
    $request_stack->push(Request::create('/foo'));
    $temp_context = new UrlCacheContext($request_stack);
306 307 308 309 310
    $this->container->set('cache_context.url', $temp_context);
    $old_cid = $cid;
    $build = $this->getBlockRenderArray();
    $cid = drupal_render_cid_create($build);
    drupal_render($build);
311
    $this->assertTrue($this->container->get('cache.render', $cid), 'The block render element has been cached.');
312 313 314 315
    $this->assertNotEqual($cid, $old_cid, 'The cache ID has changed.');
    $this->container->set('cache_context.url', $original_url_cache_context);

    // Restore the previous request method.
316
    $request->setMethod($request_method);
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
  }

  /**
   * Sets the test block's cache configuration.
   *
   * @param array $cache_config
   *   The desired cache configuration.
   */
  protected function setBlockCacheConfig(array $cache_config) {
    $block = $this->block->getPlugin();
    $block->setConfigurationValue('cache', $cache_config);
    $this->block->save();
  }

  /**
   * Get a fully built render array for a block.
   *
   * @return array
   *   The render array.
   */
  protected function getBlockRenderArray() {
    $build = $this->container->get('entity.manager')->getViewBuilder('block')->view($this->block, 'block');

    // Mock the build array to not require the theme registry.
    unset($build['#theme']);

    return $build;
  }

}