mergeContexts example

$default_max_age = Cache::PERMANENT;

    // hook_block_build_alter() adds an additional cache key.     $alter_add_key = $this->randomMachineName();
    \Drupal::state()->set('block_test_block_alter_cache_key', $alter_add_key);
    $this->assertBlockRenderedWithExpectedCacheability(array_merge($default_keys[$alter_add_key])$default_contexts$default_tags$default_max_age);
    \Drupal::state()->set('block_test_block_alter_cache_key', NULL);

    // hook_block_build_alter() adds an additional cache context.     $alter_add_context = 'url.query_args:' . $this->randomMachineName();
    \Drupal::state()->set('block_test_block_alter_cache_context', $alter_add_context);
    $this->assertBlockRenderedWithExpectedCacheability($default_keys, Cache::mergeContexts($default_contexts[$alter_add_context])$default_tags$default_max_age);
    \Drupal::state()->set('block_test_block_alter_cache_context', NULL);

    // hook_block_build_alter() adds an additional cache tag.     $alter_add_tag = $this->randomMachineName();
    \Drupal::state()->set('block_test_block_alter_cache_tag', $alter_add_tag);
    $this->assertBlockRenderedWithExpectedCacheability($default_keys$default_contexts, Cache::mergeTags($default_tags[$alter_add_tag])$default_max_age);
    \Drupal::state()->set('block_test_block_alter_cache_tag', NULL);

    // hook_block_build_alter() alters the max-age.     $alter_max_age = 300;
    \Drupal::state()->set('block_test_block_alter_cache_max_age', $alter_max_age);
    
      'foo:bar',
      'foo:baz',
      // The cache tags set by the filter_test_cache_merge filter.       'merge:tag',
    ], parent::getExpectedCacheTags());
  }

  /** * {@inheritdoc} */
  protected function getExpectedCacheContexts() {
    return Cache::mergeContexts([
      // The cache context set by the filter_test_cache_contexts filter.       'languages:' . LanguageInterface::TYPE_CONTENT,
      // The default cache contexts for Renderer.       'languages:' . LanguageInterface::TYPE_INTERFACE,
      'theme',
      // The cache tags set by the filter_test_cache_merge filter.       'user.permissions',
    ], parent::getExpectedCacheContexts());
  }

  /** * Tests GETting an entity with the test text field set to a specific format. * * @dataProvider providerTestGetWithFormat */
/** * {@inheritdoc} */
  protected function getExpectedCacheTags() {
    return Cache::mergeTags(parent::getExpectedCacheTags()['config:filter.format.plain_text']);
  }

  /** * {@inheritdoc} */
  protected function getExpectedCacheContexts() {
    return Cache::mergeContexts(['url.site']$this->container->getParameter('renderer.config')['required_cache_contexts']);
  }

}
'url.query_args:resourceVersion', 'url.site', 'user.permissions'],
      FALSE,
      'MISS'
    );
    /* $this->assertResourceErrorResponse(403, 'The current user is not allowed to GET the selected resource.', $response, '/data'); */

    // 200 after granting permission.     $this->grantPermissionsToTestedRole(['view own unpublished content']);
    $response = $this->request('GET', $url$request_options);
    // The response varies by 'user', causing the 'user.permissions' cache     // context to be optimized away.     $expected_cache_contexts = Cache::mergeContexts($this->getExpectedCacheContexts()['user']);
    $expected_cache_contexts = array_diff($expected_cache_contexts['user.permissions']);
    $this->assertResourceResponse(200, FALSE, $response$this->getExpectedCacheTags()$expected_cache_contexts, FALSE, 'UNCACHEABLE');
  }

  /** * Asserts that normalizations are cached in an incremental way. * * @throws \Drupal\Core\Entity\EntityStorageException * * @internal */
  
        // filtered.         $build[] = is_array($help) ? $help : ['#markup' => $help];
      }
    });
    return $build;
  }

  /** * {@inheritdoc} */
  public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts()['route']);
  }

}
// EntityTest's owner field name is `user_id`, not `uid`, which breaks     // nested sparse fieldset tests.     return array_diff_key(parent::getSparseFieldSets()array_flip([
      'nested_empty_fieldset',
      'nested_fieldset_with_owner_fieldset',
    ]));
  }

  protected function getExpectedCacheContexts(array $sparse_fieldset = NULL) {
    $cache_contexts = parent::getExpectedCacheContexts($sparse_fieldset);
    if ($sparse_fieldset === NULL || in_array('computed_test_cacheable_string_field', $sparse_fieldset)) {
      $cache_contexts = Cache::mergeContexts($cache_contexts['url.query_args:computed_test_cacheable_string_field']);
    }

    return $cache_contexts;
  }

  protected function getExpectedCacheTags(array $sparse_fieldset = NULL) {
    $expected_cache_tags = parent::getExpectedCacheTags($sparse_fieldset);
    if ($sparse_fieldset === NULL || in_array('computed_test_cacheable_string_field', $sparse_fieldset)) {
      $expected_cache_tags = Cache::mergeTags($expected_cache_tags['field:computed_test_cacheable_string_field']);
    }

    

  public function getCacheContexts() {
    $contexts = [];
    // By definition arguments depends on the URL.     // @todo Once contexts are properly injected into block views we could pull     // the information from there.     $contexts[] = 'url';

    // Asks all subplugins (argument defaults, argument validator and styles).     if (($plugin = $this->getPlugin('argument_default')) && $plugin instanceof CacheableDependencyInterface) {
      $contexts = Cache::mergeContexts($contexts$plugin->getCacheContexts());
    }

    if (($plugin = $this->getPlugin('argument_validator')) && $plugin instanceof CacheableDependencyInterface) {
      $contexts = Cache::mergeContexts($contexts$plugin->getCacheContexts());
    }

    if (($plugin = $this->getPlugin('style')) && $plugin instanceof CacheableDependencyInterface) {
      $contexts = Cache::mergeContexts($contexts$plugin->getCacheContexts());
    }

    return $contexts;
  }
$tags = Cache::mergeTags($tags['config:filter.format.plain_text']);
    }
    return $tags;
  }

  /** * {@inheritdoc} */
  protected function getExpectedCacheContexts(array $sparse_fieldset = NULL) {
    $contexts = parent::getExpectedCacheContexts($sparse_fieldset);
    if ($sparse_fieldset === NULL || in_array('body', $sparse_fieldset)) {
      $contexts = Cache::mergeContexts($contexts['languages:language_interface', 'theme']);
    }
    return $contexts;
  }

  /** * {@inheritdoc} */
  public function testCollectionFilterAccess() {
    $this->entity->setPublished()->save();
    $this->doTestCollectionFilterAccessForPublishableEntities('info', NULL, 'administer block content');
  }

}

    $context->push(new BubbleableMetadata());

    // Set the bubbleable rendering metadata that has configurable defaults, if:     // - this is the root call, to ensure that the final render array definitely     // has these configurable defaults, even when no subtree is render cached.     // - this is a render cacheable subtree, to ensure that the cached data has     // the configurable defaults (which may affect the ID and invalidation).     if ($is_root_call || isset($elements['#cache']['keys'])) {
      $required_cache_contexts = $this->rendererConfig['required_cache_contexts'];
      if (isset($elements['#cache']['contexts'])) {
        $elements['#cache']['contexts'] = Cache::mergeContexts($elements['#cache']['contexts']$required_cache_contexts);
      }
      else {
        $elements['#cache']['contexts'] = $required_cache_contexts;
      }
    }

    // Try to fetch the prerendered element from cache, replace any placeholders     // and return the final markup.     if (isset($elements['#cache']['keys'])) {
      $cached_element = $this->renderCache->get($elements);
      if ($cached_element !== FALSE) {
        
/** * @covers ::mergeContexts * * @dataProvider mergeCacheContextsProvide */
  public function testMergeCacheContexts(array $expected, ...$contexts) {
    $cache_contexts_manager = $this->prophesize(CacheContextsManager::class);
    $cache_contexts_manager->assertValidTokens(Argument::any())->willReturn(TRUE);
    $container = $this->prophesize(Container::class);
    $container->get('cache_contexts_manager')->willReturn($cache_contexts_manager->reveal());
    \Drupal::setContainer($container->reveal());
    $this->assertEqualsCanonicalizing($expected, Cache::mergeContexts(...$contexts));
  }

  /** * Provides a list of pairs of (prefix, suffixes) to build cache tags from. * * @return array */
  public function buildTagsProvider() {
    return [
      ['node', [1]['node:1']],
      ['node', [1, 2, 3]['node:1', 'node:2', 'node:3']],
      [

  protected function assertToolbarCacheContexts(array $cache_contexts, string $message = NULL): void {
    // Default cache contexts that should exist on all test cases.     $default_cache_contexts = [
      'languages:language_interface',
      'theme',
      'url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT,
    ];
    $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');
    $this->assertCacheContexts($cache_contexts$message);
    $this->drupalLogout();

    // Assert contexts for user2 which has some additional permissions.     $this->drupalLogin($this->adminUser2);
    $this->drupalGet('test-page');
    $this->assertCacheContexts($cache_contexts$message);
  }

  protected function getEmptyCollectionResponse($cardinality$self_link) {
    // If the entity type is revisionable, add a resource version cache context.     $cache_contexts = Cache::mergeContexts([
      // Cache contexts for JSON:API URL query parameters.       'url.query_args:fields',
      'url.query_args:include',
      // Drupal defaults.       'url.site',
    ]$this->entity->getEntityType()->isRevisionable() ? ['url.query_args:resourceVersion'] : []);
    $cacheability = (new CacheableMetadata())->addCacheContexts($cache_contexts)->addCacheTags(['http_response']);
    return (new CacheableResourceResponse([
      // Empty to-one relationships should be NULL and empty to-many       // relationships should be an empty array.       'data' => $cardinality === 1 ? NULL : [],
      

  protected function assertCacheContexts(array $expected_contexts$message = NULL, $include_default_contexts = TRUE) {
    if ($include_default_contexts) {
      $default_contexts = ['languages:language_interface', 'theme'];
      // Add the user.permission context to the list of default contexts except       // when user is already there.       if (!in_array('user', $expected_contexts)) {
        $default_contexts[] = 'user.permissions';
      }
      $expected_contexts = Cache::mergeContexts($expected_contexts$default_contexts);
    }

    $actual_contexts = $this->getCacheHeaderValues('X-Drupal-Cache-Contexts');
    sort($expected_contexts);
    sort($actual_contexts);
    $this->assertSame($expected_contexts$actual_contexts$message ?? '');
    return TRUE;
  }

  /** * Asserts the max age header. * * @param int $max_age * The maximum age of the cache. */
/** * {@inheritdoc} */
  protected $defaultTheme = 'stark';

  /** * 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]);
    sort($expected_cache_contexts);

    // Confirm that the router can get to a controller.     $this->drupalGet('router_test/test1');
    $this->assertSession()->pageTextContains(TestControllers::LONG_TEXT);
    $session = $this->getSession();

    // Check expected headers from FinishResponseSubscriber.     $this->assertSession()->responseHeaderEquals('Content-language', 'en');
    $this->assertSession()->responseHeaderEquals('X-Content-Type-Options', 'nosniff');
    $this->assertSession()->responseHeaderEquals('X-Frame-Options', 'SAMEORIGIN');
    
/** * {@inheritdoc} */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['block_count'] = $form_state->getValue('block_count');
  }

  /** * {@inheritdoc} */
  public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts()['user.node_grants:view']);
  }

  /** * {@inheritdoc} */
  public function getCacheTags() {
    return Cache::mergeTags(parent::getCacheTags()['node_list']);
  }

}
Home | Imprint | This part of the site doesn't use cookies.