BlockViewBuilderTest.php 13 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 12 13 14
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Cache\UrlCacheContext;
use Drupal\simpletest\DrupalUnitTestBase;
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\HttpFoundation\RequestStack;
16 17 18

/**
 * Tests the block view builder.
19 20
 *
 * @group block
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
 */
class BlockViewBuilderTest extends DrupalUnitTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('block', 'block_test', 'system');

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

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

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

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

    \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();

65
    $this->container->get('cache.render')->deleteAll();
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
  }

  /**
   * 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.
    $entity = entity_load('block', 'test_block1');
    $output = entity_view($entity, 'block');
    $expected = array();
    $expected[] = '<div class="block block-block-test" id="block-test-block1">';
    $expected[] = '  ';
    $expected[] = '    ';
    $expected[] = '';
    $expected[] = '  <div class="content">';
    $expected[] = '          ';
    $expected[] = '      </div>';
    $expected[] = '</div>';
    $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.
98
    Html::resetSeenIds();
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 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 148 149 150 151 152

    // 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();
    $expected[] = '<div class="block block-block-test" id="block-test-block2">';
    $expected[] = '  ';
    $expected[] = '      <h2>Powered by Bananas</h2>';
    $expected[] = '    ';
    $expected[] = '';
    $expected[] = '  <div class="content">';
    $expected[] = '          ';
    $expected[] = '      </div>';
    $expected[] = '</div>';
    $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.
153 154 155
    $request = \Drupal::request();
    $request_method = $request->server->get('REQUEST_METHOD');
    $request->setMethod('GET');
156 157 158 159 160 161 162 163 164 165 166 167 168 169

    // 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);
170
    $this->assertTrue($this->container->get('cache.render')->get($cid), 'The block render element has been cached.');
171 172 173

    // Re-save the block and check that the cache entry has been deleted.
    $this->block->save();
174
    $this->assertFalse($this->container->get('cache.render')->get($cid), 'The block render cache entry has been cleared when the block was saved.');
175 176 177 178

    // 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']);
179 180 181 182
    // Re-add the block because \Drupal\block\BlockViewBuilder::buildBlock()
    // removes it.
    $build['#block'] = $this->block;

183
    drupal_render($build);
184
    $this->assertTrue($this->container->get('cache.render')->get($cid), 'The block render element has been cached.');
185
    $this->block->delete();
186
    $this->assertFalse($this->container->get('cache.render')->get($cid), 'The block render cache entry has been cleared when the block was deleted.');
187 188

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

  /**
   * 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.
218 219 220
    $request = \Drupal::request();
    $request_method = $request->server->get('REQUEST_METHOD');
    $request->setMethod('GET');
221 222

    $default_keys = array('entity_view', 'block', 'test_block', 'en', 'cache_context.theme');
223
    $default_tags = array('block_view' => TRUE, 'block' => array('test_block'), 'theme' => 'stark', 'block_plugin' => array('test_cache'));
224 225 226 227 228

    // Advanced: cached block, but an alter hook adds an additional cache key.
    $this->setBlockCacheConfig(array(
      'max_age' => 600,
    ));
229
    $alter_add_key = $this->randomMachineName();
230 231 232 233 234 235
    \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), '');
236
    $cache_entry = $this->container->get('cache.render')->get($cid);
237
    $this->assertTrue($cache_entry, 'The block render element has been cached with the expected cache ID.');
238 239
    $expected_flattened_tags = array('block_view:1', 'block:test_block', 'theme:stark', 'block_plugin:test_cache', 'rendered:1');
    $this->assertIdentical($cache_entry->tags, $expected_flattened_tags, 'The block render element has been cached with the expected cache tags.');
240
    $this->container->get('cache.render')->delete($cid);
241 242

    // Advanced: cached block, but an alter hook adds an additional cache tag.
243
    $alter_add_tag = $this->randomMachineName();
244 245 246 247 248 249
    \Drupal::state()->set('block_test_view_alter_cache_tag', $alter_add_tag);
    $expected_tags = NestedArray::mergeDeep($default_tags, array($alter_add_tag => TRUE));
    $build = $this->getBlockRenderArray();
    $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), '');
250
    $cache_entry = $this->container->get('cache.render')->get($cid);
251
    $this->assertTrue($cache_entry, 'The block render element has been cached with the expected cache ID.');
252 253
    $expected_flattened_tags = array('block_view:1', 'block:test_block', 'theme:stark', 'block_plugin:test_cache', $alter_add_tag . ':1', 'rendered:1');
    $this->assertIdentical($cache_entry->tags, $expected_flattened_tags, 'The block render element has been cached with the expected cache tags.');
254
    $this->container->get('cache.render')->delete($cid);
255 256 257 258 259 260 261 262 263 264

    // 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.
265
    $request->setMethod($request_method);
266 267 268 269 270 271 272 273 274 275 276 277
  }

  /**
   * 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.
278 279 280
    $request = \Drupal::request();
    $request_method = $request->server->get('REQUEST_METHOD');
    $request->setMethod('GET');
281 282 283 284 285 286 287 288

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

    // 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);
300
    $this->assertTrue($this->container->get('cache.render', $cid), 'The block render element has been cached.');
301 302 303 304
    $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');
305 306 307
    $request_stack = new RequestStack();
    $request_stack->push(Request::create('/foo'));
    $temp_context = new UrlCacheContext($request_stack);
308 309 310 311 312
    $this->container->set('cache_context.url', $temp_context);
    $old_cid = $cid;
    $build = $this->getBlockRenderArray();
    $cid = drupal_render_cid_create($build);
    drupal_render($build);
313
    $this->assertTrue($this->container->get('cache.render', $cid), 'The block render element has been cached.');
314 315 316 317
    $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.
318
    $request->setMethod($request_method);
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 347 348
  }

  /**
   * 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;
  }

}