本文整理汇总了PHP中Drupal\Core\Cache\Cache::mergeContexts方法的典型用法代码示例。如果您正苦于以下问题:PHP Cache::mergeContexts方法的具体用法?PHP Cache::mergeContexts怎么用?PHP Cache::mergeContexts使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\Core\Cache\Cache
的用法示例。
在下文中一共展示了Cache::mergeContexts方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getCacheContexts
/**
* {@inheritdoc}
*/
public function getCacheContexts()
{
// The block by itself doesn't really vary by user, but some of its
// implementations are (collection module, I'm looking at you). For the sake
// of semplicity, we add the user context here already.
$contexts = parent::getCacheContexts();
return Cache::mergeContexts($contexts, ['user']);
}
示例2: getCacheContexts
/**
* {@inheritdoc}
*/
public function getCacheContexts()
{
return Cache::mergeContexts(parent::getCacheContexts(), ['route.book_navigation']);
}
示例3: testBlock
/**
* Tests that the block is cached with the correct contexts and tags.
*/
public function testBlock()
{
$block = $this->drupalPlaceBlock('block_content:' . $this->entity->uuid());
$build = $this->container->get('entity.manager')->getViewBuilder('block')->view($block, 'block');
// Render the block.
// @todo The request stack manipulation won't be necessary once
// https://www.drupal.org/node/2367555 is fixed and the
// corresponding $request->isMethodSafe() checks are removed from
// Drupal\Core\Render\Renderer.
$request_stack = $this->container->get('request_stack');
$request_stack->push(new Request());
$this->container->get('renderer')->renderRoot($build);
$request_stack->pop();
// Expected keys, contexts, and tags for the block.
// @see \Drupal\block\BlockViewBuilder::viewMultiple()
$expected_block_cache_keys = ['entity_view', 'block', $block->id()];
$expected_block_cache_contexts = ['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme'];
$expected_block_cache_tags = Cache::mergeTags(['block_view', 'rendered'], $block->getCacheTags(), $block->getPlugin()->getCacheTags());
// Expected contexts and tags for the BlockContent entity.
// @see \Drupal\Core\Entity\EntityViewBuilder::getBuildDefaults().
$expected_entity_cache_contexts = ['theme'];
$expected_entity_cache_tags = Cache::mergeTags(['block_content_view'], $this->entity->getCacheTags(), $this->getAdditionalCacheTagsForEntity($this->entity));
// Verify that what was render cached matches the above expectations.
$cid = $this->createCacheId($expected_block_cache_keys, $expected_block_cache_contexts);
$redirected_cid = $this->createCacheId($expected_block_cache_keys, Cache::mergeContexts($expected_block_cache_contexts, $expected_entity_cache_contexts));
$this->verifyRenderCache($cid, Cache::mergeTags($expected_block_cache_tags, $expected_entity_cache_tags), $cid !== $redirected_cid ? $redirected_cid : NULL);
}
示例4: viewMultiple
/**
* {@inheritdoc}
*/
public function viewMultiple(array $entities = array(), $view_mode = 'full', $langcode = NULL)
{
// @todo Remove when https://www.drupal.org/node/2453059 lands.
$default_cache_contexts = ['languages', 'theme'];
/** @var \Drupal\block\BlockInterface[] $entities */
$build = array();
foreach ($entities as $entity) {
$entity_id = $entity->id();
$plugin = $entity->getPlugin();
$plugin_id = $plugin->getPluginId();
$base_id = $plugin->getBaseId();
$derivative_id = $plugin->getDerivativeId();
$configuration = $plugin->getConfiguration();
// Create the render array for the block as a whole.
// @see template_preprocess_block().
$build[$entity_id] = array('#theme' => 'block', '#attributes' => array(), '#contextual_links' => array('block' => array('route_parameters' => array('block' => $entity->id()))), '#weight' => $entity->getWeight(), '#configuration' => $configuration, '#plugin_id' => $plugin_id, '#base_plugin_id' => $base_id, '#derivative_plugin_id' => $derivative_id, '#id' => $entity->id(), '#cache' => ['contexts' => Cache::mergeContexts($default_cache_contexts, $plugin->getCacheContexts()), 'tags' => Cache::mergeTags($this->getCacheTags(), $entity->getCacheTags(), $plugin->getCacheTags()), 'max-age' => $plugin->getCacheMaxAge()], '#block' => $entity);
$build[$entity_id]['#configuration']['label'] = String::checkPlain($configuration['label']);
if ($plugin->isCacheable()) {
$build[$entity_id]['#pre_render'][] = array($this, 'buildBlock');
// Generic cache keys, with the block plugin's custom keys appended.
$default_cache_keys = array('entity_view', 'block', $entity->id());
$build[$entity_id]['#cache']['keys'] = array_merge($default_cache_keys, $plugin->getCacheKeys());
} else {
$build[$entity_id] = $this->buildBlock($build[$entity_id]);
}
// Don't run in ::buildBlock() to ensure cache keys can be altered. If an
// alter hook wants to modify the block contents, it can append another
// #pre_render hook.
$this->moduleHandler()->alter(array('block_view', "block_view_{$base_id}"), $build[$entity_id], $plugin);
}
return $build;
}
示例5: viewMultiple
/**
* {@inheritdoc}
*/
public function viewMultiple(array $entities = array(), $view_mode = 'full', $langcode = NULL)
{
/** @var \Drupal\block\BlockInterface[] $entities */
$build = array();
foreach ($entities as $entity) {
$entity_id = $entity->id();
$plugin = $entity->getPlugin();
$cache_tags = Cache::mergeTags($this->getCacheTags(), $entity->getCacheTags());
$cache_tags = Cache::mergeTags($cache_tags, $plugin->getCacheTags());
// Create the render array for the block as a whole.
// @see template_preprocess_block().
$build[$entity_id] = array('#cache' => ['keys' => ['entity_view', 'block', $entity->id()], 'contexts' => Cache::mergeContexts($entity->getCacheContexts(), $plugin->getCacheContexts()), 'tags' => $cache_tags, 'max-age' => $plugin->getCacheMaxAge()], '#weight' => $entity->getWeight());
// Allow altering of cacheability metadata or setting #create_placeholder.
$this->moduleHandler->alter(['block_build', "block_build_" . $plugin->getBaseId()], $build[$entity_id], $plugin);
if ($plugin instanceof MainContentBlockPluginInterface || $plugin instanceof TitleBlockPluginInterface) {
// Immediately build a #pre_render-able block, since this block cannot
// be built lazily.
$build[$entity_id] += static::buildPreRenderableBlock($entity, $this->moduleHandler());
} else {
// Assign a #lazy_builder callback, which will generate a #pre_render-
// able block lazily (when necessary).
$build[$entity_id] += ['#lazy_builder' => [static::class . '::lazyBuilder', [$entity_id, $view_mode, $langcode]]];
}
}
return $build;
}
示例6: testFinishResponseSubscriber
/**
* Confirms that our FinishResponseSubscriber logic works properly.
*/
public function testFinishResponseSubscriber()
{
$renderer_required_cache_contexts = ['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions'];
$expected_cache_contexts = Cache::mergeContexts($renderer_required_cache_contexts, ['url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT]);
// Confirm that the router can get to a controller.
$this->drupalGet('router_test/test1');
$this->assertRaw('test1', 'The correct string was returned because the route was successful.');
// Check expected headers from FinishResponseSubscriber.
$headers = $this->drupalGetHeaders();
$this->assertEqual($headers['x-ua-compatible'], 'IE=edge');
$this->assertEqual($headers['content-language'], 'en');
$this->assertEqual($headers['x-content-type-options'], 'nosniff');
$this->assertEqual($headers['x-frame-options'], 'SAMEORIGIN');
$this->drupalGet('router_test/test2');
$this->assertRaw('test2', 'The correct string was returned because the route was successful.');
// Check expected headers from FinishResponseSubscriber.
$headers = $this->drupalGetHeaders();
$this->assertEqual($headers['x-drupal-cache-contexts'], implode(' ', $expected_cache_contexts));
$this->assertEqual($headers['x-drupal-cache-tags'], 'config:user.role.anonymous rendered');
// Confirm that the page wrapping is being added, so we're not getting a
// raw body returned.
$this->assertRaw('</html>', 'Page markup was found.');
// In some instances, the subrequest handling may get confused and render
// a page inception style. This test verifies that is not happening.
$this->assertNoPattern('#</body>.*</body>#s', 'There was no double-page effect from a misrendered subrequest.');
// Confirm that route-level access check's cacheability is applied to the
// X-Drupal-Cache-Contexts and X-Drupal-Cache-Tags headers.
// 1. controller result: render array, globally cacheable route access.
$this->drupalGet('router_test/test18');
$headers = $this->drupalGetHeaders();
$this->assertEqual($headers['x-drupal-cache-contexts'], implode(' ', Cache::mergeContexts($renderer_required_cache_contexts, ['url'])));
$this->assertEqual($headers['x-drupal-cache-tags'], 'config:user.role.anonymous foo rendered');
// 2. controller result: render array, per-role cacheable route access.
$this->drupalGet('router_test/test19');
$headers = $this->drupalGetHeaders();
$this->assertEqual($headers['x-drupal-cache-contexts'], implode(' ', Cache::mergeContexts($renderer_required_cache_contexts, ['url', 'user.roles'])));
$this->assertEqual($headers['x-drupal-cache-tags'], 'config:user.role.anonymous foo rendered');
// 3. controller result: Response object, globally cacheable route access.
$this->drupalGet('router_test/test1');
$headers = $this->drupalGetHeaders();
$this->assertFalse(isset($headers['x-drupal-cache-contexts']));
$this->assertFalse(isset($headers['x-drupal-cache-tags']));
// 4. controller result: Response object, per-role cacheable route access.
$this->drupalGet('router_test/test20');
$headers = $this->drupalGetHeaders();
$this->assertFalse(isset($headers['x-drupal-cache-contexts']));
$this->assertFalse(isset($headers['x-drupal-cache-tags']));
// 5. controller result: CacheableResponse object, globally cacheable route access.
$this->drupalGet('router_test/test21');
$headers = $this->drupalGetHeaders();
$this->assertEqual($headers['x-drupal-cache-contexts'], '');
$this->assertEqual($headers['x-drupal-cache-tags'], '');
// 6. controller result: CacheableResponse object, per-role cacheable route access.
$this->drupalGet('router_test/test22');
$headers = $this->drupalGetHeaders();
$this->assertEqual($headers['x-drupal-cache-contexts'], 'user.roles');
$this->assertEqual($headers['x-drupal-cache-tags'], '');
}
示例7: testLinkCacheability
/**
* Tests that #type=link bubbles outbound route/path processors' cacheability.
*/
function testLinkCacheability()
{
$cases = [['Regular link', 'internal:/user', [], ['contexts' => [], 'tags' => [], 'max-age' => Cache::PERMANENT]], ['Regular link, absolute', 'internal:/user', ['absolute' => TRUE], ['contexts' => ['url.site'], 'tags' => [], 'max-age' => Cache::PERMANENT]], ['Route processor link', 'route:system.run_cron', [], ['contexts' => [], 'tags' => [], 'max-age' => 0]], ['Route processor link, absolute', 'route:system.run_cron', ['absolute' => TRUE], ['contexts' => ['url.site'], 'tags' => [], 'max-age' => 0]], ['Path processor link', 'internal:/user/1', [], ['contexts' => [], 'tags' => ['user:1'], 'max-age' => Cache::PERMANENT]], ['Path processor link, absolute', 'internal:/user/1', ['absolute' => TRUE], ['contexts' => ['url.site'], 'tags' => ['user:1'], 'max-age' => Cache::PERMANENT]]];
foreach ($cases as $case) {
list($title, $uri, $options, $expected_cacheability) = $case;
$expected_cacheability['contexts'] = Cache::mergeContexts($expected_cacheability['contexts'], ['languages:language_interface', 'theme']);
$link = ['#type' => 'link', '#title' => $title, '#options' => $options, '#url' => Url::fromUri($uri)];
\Drupal::service('renderer')->renderRoot($link);
$this->pass($title);
$this->assertEqual($expected_cacheability, $link['#cache']);
}
}
示例8: viewMultiple
/**
* {@inheritdoc}
*/
public function viewMultiple(array $entities = array(), $view_mode = 'full', $langcode = NULL)
{
/** @var \Drupal\block\BlockInterface[] $entities */
$build = array();
foreach ($entities as $entity) {
$entity_id = $entity->id();
$plugin = $entity->getPlugin();
$plugin_id = $plugin->getPluginId();
$base_id = $plugin->getBaseId();
$derivative_id = $plugin->getDerivativeId();
$configuration = $plugin->getConfiguration();
$cache_tags = Cache::mergeTags($this->getCacheTags(), $entity->getCacheTags());
$cache_tags = Cache::mergeTags($cache_tags, $plugin->getCacheTags());
// Create the render array for the block as a whole.
// @see template_preprocess_block().
$build[$entity_id] = array('#theme' => 'block', '#attributes' => array(), '#contextual_links' => array('block' => array('route_parameters' => array('block' => $entity->id()))), '#weight' => $entity->getWeight(), '#configuration' => $configuration, '#plugin_id' => $plugin_id, '#base_plugin_id' => $base_id, '#derivative_plugin_id' => $derivative_id, '#id' => $entity->id(), '#cache' => ['keys' => ['entity_view', 'block', $entity->id()], 'contexts' => Cache::mergeContexts($entity->getCacheContexts(), $plugin->getCacheContexts()), 'tags' => $cache_tags, 'max-age' => $plugin->getCacheMaxAge()], '#pre_render' => [[$this, 'buildBlock']], '#block' => $entity);
$build[$entity_id]['#configuration']['label'] = SafeMarkup::checkPlain($configuration['label']);
// Don't run in ::buildBlock() to ensure cache keys can be altered. If an
// alter hook wants to modify the block contents, it can append another
// #pre_render hook.
$this->moduleHandler()->alter(array('block_view', "block_view_{$base_id}"), $build[$entity_id], $plugin);
}
return $build;
}
示例9: assertBlockRenderedWithExpectedCacheability
/**
* Asserts that a block is built/rendered/cached with expected cacheability.
*
* @param string[] $expected_keys
* The expected cache keys.
* @param string[] $expected_contexts
* The expected cache contexts.
* @param string[] $expected_tags
* The expected cache tags.
* @param int $expected_max_age
* The expected max-age.
*/
protected function assertBlockRenderedWithExpectedCacheability(array $expected_keys, array $expected_contexts, array $expected_tags, $expected_max_age)
{
$required_cache_contexts = ['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions'];
// Check that the expected cacheability metadata is present in:
// - the built render array;
$this->pass('Built render array');
$build = $this->getBlockRenderArray();
$this->assertIdentical($expected_keys, $build['#cache']['keys']);
$this->assertIdentical($expected_contexts, $build['#cache']['contexts']);
$this->assertIdentical($expected_tags, $build['#cache']['tags']);
$this->assertIdentical($expected_max_age, $build['#cache']['max-age']);
$this->assertFalse(isset($build['#create_placeholder']));
// - the rendered render array;
$this->pass('Rendered render array');
$this->renderer->renderRoot($build);
// - the render cache item.
$this->pass('Render cache item');
$final_cache_contexts = Cache::mergeContexts($expected_contexts, $required_cache_contexts);
$cid = implode(':', $expected_keys) . ':' . implode(':', \Drupal::service('cache_contexts_manager')->convertTokensToKeys($final_cache_contexts)->getKeys());
$cache_item = $this->container->get('cache.render')->get($cid);
$this->assertTrue($cache_item, 'The block render element has been cached with the expected cache ID.');
$this->assertIdentical(Cache::mergeTags($expected_tags, ['rendered']), $cache_item->tags);
$this->assertIdentical($final_cache_contexts, $cache_item->data['#cache']['contexts']);
$this->assertIdentical($expected_tags, $cache_item->data['#cache']['tags']);
$this->assertIdentical($expected_max_age, $cache_item->data['#cache']['max-age']);
$this->container->get('cache.render')->delete($cid);
}
示例10: assertToolbarCacheContexts
/**
* Tests that cache contexts are applied for both users.
*
* @param string[] $cache_contexts
* Expected cache contexts for both users.
* @param string $message
* (optional) A verbose message to output.
*
* @return
* TRUE if the assertion succeeded, FALSE otherwise.
*/
protected function assertToolbarCacheContexts(array $cache_contexts, $message = NULL)
{
// Default cache contexts that should exist on all test cases.
$default_cache_contexts = ['languages:language_interface', 'theme'];
$cache_contexts = Cache::mergeContexts($default_cache_contexts, $cache_contexts);
// Assert contexts for user1 which has only default permissions.
$this->drupalLogin($this->adminUser);
$this->drupalGet('test-page');
$return = $this->assertCacheContexts($cache_contexts);
$this->drupalLogout();
// Assert contexts for user2 which has some additional permissions.
$this->drupalLogin($this->adminUser2);
$this->drupalGet('test-page');
$return = $return && $this->assertCacheContexts($cache_contexts);
if ($return) {
$this->pass($message);
} else {
$this->fail($message);
}
return $return;
}
示例11: set
//.........这里部分代码省略.........
//
// Additionally, suppose that:
// - C only exists for a 'b' context value of 'b1'
// - D only exists for a 'b' context value of 'b2'
// This is an acceptable variation, since B specifies that its contents
// vary on context 'b'.
//
// A naive implementation of cache redirection would result in the
// following:
// - When a request is processed where context 'b' = 'b1', what would be
// cached for a $pre_bubbling_cid of 'foo' is:
// [
// '#cache_redirect' => TRUE,
// '#cache' => [
// ...
// 'contexts' => ['b', 'c'],
// ],
// ]
// - When a request is processed where context 'b' = 'b2', we would
// retrieve the above from cache, but when following that redirection,
// get a cache miss, since we're processing a 'b' context value that
// has not yet been cached. Given the cache miss, we would continue
// with rendering the structure, perform the required context bubbling
// and then overwrite the above item with:
// [
// '#cache_redirect' => TRUE,
// '#cache' => [
// ...
// 'contexts' => ['b', 'd'],
// ],
// ]
// - Now, if a request comes in where context 'b' = 'b1' again, the above
// would redirect to a cache key that doesn't exist, since we have not
// yet cached an item that includes 'b'='b1' and something for 'd'. So
// we would process this request as a cache miss, at the end of which,
// we would overwrite the above item back to:
// [
// '#cache_redirect' => TRUE,
// '#cache' => [
// ...
// 'contexts' => ['b', 'c'],
// ],
// ]
// - The above would always result in accurate renderings, but would
// result in poor performance as we keep processing requests as cache
// misses even though the target of the redirection is cached, and
// it's only the redirection element itself that is creating the
// ping-pong problem.
//
// A way to resolve the ping-pong problem is to eventually reach a cache
// state where the redirection element includes all of the contexts used
// throughout all requests:
// [
// '#cache_redirect' => TRUE,
// '#cache' => [
// ...
// 'contexts' => ['b', 'c', 'd'],
// ],
// ]
//
// We can't reach that state right away, since we don't know what the
// result of future requests will be, but we can incrementally move
// towards that state by progressively merging the 'contexts' value
// across requests. That's the strategy employed below and tested in
// \Drupal\Tests\Core\Render\RendererBubblingTest::testConditionalCacheContextBubblingSelfHealing().
// The set of cache contexts for this element, including the bubbled ones,
// for which we are handling a cache miss.
$cache_contexts = $data['#cache']['contexts'];
// Get the contexts by which this element should be varied according to
// the current redirecting cache item, if any.
$stored_cache_contexts = [];
$stored_cache_tags = [];
if ($stored_cache_redirect = $cache->get($pre_bubbling_cid)) {
$stored_cache_contexts = $stored_cache_redirect->data['#cache']['contexts'];
$stored_cache_tags = $stored_cache_redirect->data['#cache']['tags'];
}
// Calculate the union of the cache contexts for this request and the
// stored cache contexts.
$merged_cache_contexts = Cache::mergeContexts($stored_cache_contexts, $cache_contexts);
// Stored cache contexts incomplete: this request causes cache contexts to
// be added to the redirecting cache item.
if (array_diff($merged_cache_contexts, $stored_cache_contexts)) {
$redirect_data = ['#cache_redirect' => TRUE, '#cache' => ['keys' => $elements['#cache']['keys'], 'contexts' => $merged_cache_contexts, 'tags' => Cache::mergeTags($stored_cache_tags, $data['#cache']['tags'])]];
$cache->set($pre_bubbling_cid, $redirect_data, $expire, Cache::mergeTags($redirect_data['#cache']['tags'], ['rendered']));
}
// Current cache contexts incomplete: this request only uses a subset of
// the cache contexts stored in the redirecting cache item. Vary by these
// additional (conditional) cache contexts as well, otherwise the
// redirecting cache item would be pointing to a cache item that can never
// exist.
if (array_diff($merged_cache_contexts, $cache_contexts)) {
// Recalculate the cache ID.
$recalculated_cid_pseudo_element = ['#cache' => ['keys' => $elements['#cache']['keys'], 'contexts' => $merged_cache_contexts]];
$cid = $this->createCacheID($recalculated_cid_pseudo_element);
// Ensure the about-to-be-cached data uses the merged cache contexts.
$data['#cache']['contexts'] = $merged_cache_contexts;
}
}
$cache->set($cid, $data, $expire, Cache::mergeTags($data['#cache']['tags'], ['rendered']));
}
示例12: addCacheMetadata
/**
* Fills in the cache metadata of this view.
*
* Cache metadata is set per view and per display, and ends up being stored in
* the view's configuration. This allows Views to determine very efficiently:
* - the max-age
* - the cache contexts
* - the cache tags
*
* In other words: this allows us to do the (expensive) work of initializing
* Views plugins and handlers to determine their effect on the cacheability of
* a view at save time rather than at runtime.
*/
protected function addCacheMetadata()
{
$executable = $this->getExecutable();
$current_display = $executable->current_display;
$displays = $this->get('display');
foreach (array_keys($displays) as $display_id) {
$display =& $this->getDisplay($display_id);
$executable->setDisplay($display_id);
$cache_metadata = $executable->getDisplay()->calculateCacheMetadata();
$display['cache_metadata']['max-age'] = $cache_metadata->getCacheMaxAge();
$display['cache_metadata']['contexts'] = $cache_metadata->getCacheContexts();
$display['cache_metadata']['tags'] = $cache_metadata->getCacheTags();
// Always include at least the 'languages:' context as there will most
// probably be translatable strings in the view output.
$display['cache_metadata']['contexts'] = Cache::mergeContexts($display['cache_metadata']['contexts'], ['languages:' . LanguageInterface::TYPE_INTERFACE]);
}
// Restore the previous active display.
$executable->setDisplay($current_display);
}
示例13: renderResponse
/**
* {@inheritdoc}
*
* The entire HTML: takes a #type 'page' and wraps it in a #type 'html'.
*/
public function renderResponse(array $main_content, Request $request, RouteMatchInterface $route_match)
{
list($page, $title) = $this->prepare($main_content, $request, $route_match);
if (!isset($page['#type']) || $page['#type'] !== 'page') {
throw new \LogicException('Must be #type page');
}
$page['#title'] = $title;
// Now render the rendered page.html.twig template inside the html.html.twig
// template, and use the bubbled #attached metadata from $page to ensure we
// load all attached assets.
$html = ['#type' => 'html', 'page' => $page];
// The special page regions will appear directly in html.html.twig, not in
// page.html.twig, hence add them here, just before rendering html.html.twig.
$this->buildPageTopAndBottom($html);
// Render, but don't replace placeholders yet, because that happens later in
// the render pipeline. To not replace placeholders yet, we use
// RendererInterface::render() instead of RendererInterface::renderRoot().
// @see \Drupal\Core\Render\HtmlResponseAttachmentsProcessor.
$render_context = new RenderContext();
$this->renderer->executeInRenderContext($render_context, function () use(&$html) {
// RendererInterface::render() renders the $html render array and updates
// it in place. We don't care about the return value (which is just
// $html['#markup']), but about the resulting render array.
// @todo Simplify this when https://www.drupal.org/node/2495001 lands.
$this->renderer->render($html);
});
// RendererInterface::render() always causes bubbleable metadata to be
// stored in the render context, no need to check it conditionally.
$bubbleable_metadata = $render_context->pop();
$bubbleable_metadata->applyTo($html);
$content = $this->renderCache->getCacheableRenderArray($html);
// Also associate the required cache contexts.
// (Because we use ::render() above and not ::renderRoot(), we manually must
// ensure the HTML response varies by the required cache contexts.)
$content['#cache']['contexts'] = Cache::mergeContexts($content['#cache']['contexts'], $this->rendererConfig['required_cache_contexts']);
// Also associate the "rendered" cache tag. This allows us to invalidate the
// entire render cache, regardless of the cache bin.
$content['#cache']['tags'][] = 'rendered';
$response = new HtmlResponse($content, 200, ['Content-Type' => 'text/html; charset=UTF-8']);
return $response;
}
示例14: testRandomOrderingWithRenderCaching
/**
* Tests random ordering with tags based caching.
*
* The random sorting should opt out of caching by defining a max age of 0.
* At the same time, the row render caching still works.
*/
public function testRandomOrderingWithRenderCaching()
{
$view_random = $this->getBasicRandomView();
$display =& $view_random->storage->getDisplay('default');
$display['display_options']['cache'] = ['type' => 'tag'];
$view_random->storage->save();
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = \Drupal::service('renderer');
/** @var \Drupal\Core\Render\RenderCacheInterface $render_cache */
$render_cache = \Drupal::service('render_cache');
$original = $build = DisplayPluginBase::buildBasicRenderable($view_random->id(), 'default');
$result = $renderer->renderPlain($build);
$original['#cache'] += ['contexts' => []];
$original['#cache']['contexts'] = Cache::mergeContexts($original['#cache']['contexts'], $this->container->getParameter('renderer.config')['required_cache_contexts']);
$this->assertFalse($render_cache->get($original), 'Ensure there is no render cache entry.');
$build = DisplayPluginBase::buildBasicRenderable($view_random->id(), 'default');
$result2 = $renderer->renderPlain($build);
// Ensure that the random ordering works and don't produce the same result.
$this->assertNotEqual($result, $result2);
}
示例15: assertViewsCacheTagsFromStaticRenderArray
/**
* Asserts a view's result & render cache items' cache tags.
*
* This method starts with a pre bubbling basic render array.
*
* @param \Drupal\views\ViewExecutable $view
* The view.
* @param string[] $expected_render_array_cache_tags
* The expected render cache tags.
* @param bool $views_caching_is_enabled
* Defines whether views output / render caching is enabled.
*
* @return array
* The render array.
*/
protected function assertViewsCacheTagsFromStaticRenderArray(ViewExecutable $view, array $expected_render_array_cache_tags, $views_caching_is_enabled)
{
$original = $build = DisplayPluginBase::buildBasicRenderable($view->id(), $view->current_display ?: 'default', $view->args);
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = \Drupal::service('renderer');
/** @var \Drupal\Core\Render\RenderCacheInterface $render_cache */
$render_cache = \Drupal::service('render_cache');
// Ensure the current request is a GET request so that render caching is
// active for direct rendering of views, just like for actual requests.
/** @var \Symfony\Component\HttpFoundation\RequestStack $request_stack */
$request_stack = \Drupal::service('request_stack');
$request = new Request();
$request->server->set('REQUEST_TIME', REQUEST_TIME);
$request_stack->push($request);
$renderer->renderRoot($build);
// Render array cache tags.
$this->pass('Checking render array cache tags.');
sort($expected_render_array_cache_tags);
$this->assertEqual($build['#cache']['tags'], $expected_render_array_cache_tags);
$this->debugCacheTags($build['#cache']['tags'], $expected_render_array_cache_tags);
$this->pass('Checking Views render cache item cache tags.');
$original['#cache'] += ['contexts' => []];
$original['#cache']['contexts'] = Cache::mergeContexts($original['#cache']['contexts'], $this->container->getParameter('renderer.config')['required_cache_contexts']);
$render_cache_item = $render_cache->get($original);
if ($views_caching_is_enabled) {
$this->assertTrue(!empty($render_cache_item), 'Render cache item found.');
if ($render_cache_item) {
$this->assertEqual($render_cache_item['#cache']['tags'], $expected_render_array_cache_tags);
$this->debugCacheTags($render_cache_item['#cache']['tags'], $expected_render_array_cache_tags);
}
} else {
$this->assertFalse($render_cache_item, 'Render cache item not found.');
}
return $build;
}