convertTokensToKeys example

$cid = implode(':', $cid_parts);
    $cache_entry = \Drupal::cache('page')->get($cid);
    $expected_cache_tags = [
      'config:block_list',
      'block_view',
      'config:block.block.powered',
      'config:user.role.anonymous',
      'http_response',
      'rendered',
    ];
    sort($expected_cache_tags);
    $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
    $this->assertSame($expected_cache_tags$cache_entry->tags);
    $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:' . implode(':', $keys));
    $expected_cache_tags = [
      'block_view',
      'config:block.block.powered',
      'rendered',
    ];
    sort($expected_cache_tags);
    $this->assertSame($expected_cache_tags$cache_entry->tags);

    // The "Powered by Drupal" block is modified; verify a cache miss.
$key_data = [
        'build_info' => $build_info,
      ];
      // @todo https://www.drupal.org/node/2433591 might solve it to not require       // the pager information here.       $key_data['pager'] = [
        'page' => $this->view->getCurrentPage(),
        'items_per_page' => $this->view->getItemsPerPage(),
        'offset' => $this->view->getOffset(),
      ];
      $key_data += \Drupal::service('cache_contexts_manager')->convertTokensToKeys($this->displayHandler->getCacheMetadata()->getCacheContexts())->getKeys();

      $this->resultsKey = $this->view->storage->id() . ':' . $this->displayHandler->display['id'] . ':results:' . hash('sha256', serialize($key_data));
    }

    return $this->resultsKey;
  }

  /** * Gets an array of cache tags for the current view. * * @return string[] * An array of cache tags based on the current view. */
      [['a.b.no-optimize', 'a.b', 'a']['a.b.no-optimize', 'a']],
    ];
  }

  /** * @covers ::convertTokensToKeys */
  public function testConvertTokensToKeys() {
    $container = $this->getMockContainer();
    $cache_contexts_manager = new CacheContextsManager($container$this->getContextsFixture());

    $new_keys = $cache_contexts_manager->convertTokensToKeys([
      'foo',
      'baz:parameterA',
      'baz:parameterB',
    ]);

    $expected = [
      '[baz:parameterA]=cnenzrgreN',
      '[baz:parameterB]=cnenzrgreO',
      '[foo]=bar',
    ];
    $this->assertEquals($expected$new_keys->getKeys());
  }
      'user.node_grants:view',
      'languages:' . LanguageInterface::TYPE_INTERFACE,
      // Cache contexts associated with the route's access checking.       'user.permissions',
      // Default cache contexts of the renderer.       'theme',
      'url.query_args',
      // Attached feed.       'url.site',
    ];

    $cache_context_tags = \Drupal::service('cache_contexts_manager')->convertTokensToKeys($cache_contexts)->getCacheTags();

    // Test before there are any nodes.     $empty_node_listing_cache_tags = [
      'config:views.view.frontpage',
      'node_list',
    ];

    $render_cache_tags = Cache::mergeTags($empty_node_listing_cache_tags$cache_context_tags);
    $this->assertViewsCacheTags(
      $view,
      $empty_node_listing_cache_tags,
      
    // which adds the block config entity type's list cache tags.     $page_cache_tags = Cache::mergeTags($page_cache_tags, \Drupal::moduleHandler()->moduleExists('block') ? ['config:block_list'] : []);

    $page_cache_tags_referencing_entity = in_array('user.permissions', $this->getAccessCacheContextsForEntity($this->referencingEntity)) ? ['config:user.role.anonymous'] : [];

    $view_cache_tag = [];
    if ($this->entity->getEntityType()->hasHandlerClass('view_builder')) {
      $view_cache_tag = \Drupal::entityTypeManager()->getViewBuilder($entity_type)
        ->getCacheTags();
    }

    $context_metadata = \Drupal::service('cache_contexts_manager')->convertTokensToKeys($entity_cache_contexts);
    $cache_context_tags = $context_metadata->getCacheTags();

    // Generate the cache tags for the (non) referencing entities.     $referencing_entity_cache_tags = Cache::mergeTags($this->referencingEntity->getCacheTags(), \Drupal::entityTypeManager()->getViewBuilder('entity_test')->getCacheTags());
    // Includes the main entity's cache tags, since this entity references it.     $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags$this->entity->getCacheTags());
    $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags$this->getAdditionalCacheTagsForEntity($this->entity));
    $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags$view_cache_tag);
    $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags$cache_context_tags);
    $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags['rendered']);

    
$cache_contexts = [
      'languages:language_interface',
      'theme',
      'url.site',
      'user.node_grants:view',
      'user.permissions',
      'timezone',
    ];
    $this->assertCacheContexts($cache_contexts);

    $cache_context_tags = \Drupal::service('cache_contexts_manager')->convertTokensToKeys($cache_contexts)->getCacheTags();
    $this->assertCacheTags(Cache::mergeTags($cache_context_tags[
      'config:views.view.frontpage',
      'node:1', 'node_list',
      'node_view',
      'user:3',
    ]));

    $raw = '<comments>' . $this->node->toUrl('canonical', ['fragment' => 'comments', 'absolute' => TRUE])->toString() . '</comments>';
    $this->assertSession()->responseContains($raw);

    // Hide comments from RSS feed and check presence.

  protected function createCacheID(array &$elements) {
    // If the maximum age is zero, then caching is effectively prohibited.     if (isset($elements['#cache']['max-age']) && $elements['#cache']['max-age'] === 0) {
      return FALSE;
    }

    if (isset($elements['#cache']['keys'])) {
      $cid_parts = $elements['#cache']['keys'];
      if (!empty($elements['#cache']['contexts'])) {
        $context_cache_keys = $this->cacheContextsManager->convertTokensToKeys($elements['#cache']['contexts']);
        $cid_parts = array_merge($cid_parts$context_cache_keys->getKeys());
        CacheableMetadata::createFromRenderArray($elements)
          ->merge($context_cache_keys)
          ->applyTo($elements);
      }
      return implode(':', $cid_parts);
    }
    return FALSE;
  }

  /** * {@inheritdoc} */
$entity_test = $this->createTestEntity('entity_test');

    // Test that new entities (before they are saved for the first time) do not     // generate a cache entry.     $build = $this->container->get('entity_type.manager')->getViewBuilder('entity_test')->view($entity_test, 'full');
    $this->assertNotEmpty($build['#cache']);
    $this->assertEquals(['tags', 'contexts', 'max-age']array_keys($build['#cache']), 'The render array element of new (unsaved) entities is not cached, but does have cache tags set.');

    // Get a fully built entity view render array.     $entity_test->save();
    $build = $this->container->get('entity_type.manager')->getViewBuilder('entity_test')->view($entity_test, 'full');
    $cid_parts = array_merge($build['#cache']['keys']$cache_contexts_manager->convertTokensToKeys(['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions'])->getKeys());
    $cid = implode(':', $cid_parts);
    $bin = $build['#cache']['bin'];

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

    // Test that a cache entry is created.     $renderer->renderRoot($build);
    $this->assertNotEmpty($this->container->get('cache.' . $bin)->get($cid), 'The entity render element has been cached.');

    

  protected function verifyRenderCacheHandling() {
    // Force a request via GET so we can test the render cache.     $request = \Drupal::request();
    $request_method = $request->server->get('REQUEST_METHOD');
    $request->setMethod('GET');

    // Test that a cache entry is created.     $build = $this->getBlockRenderArray();
    $cid = 'entity_view:block:test_block:' . implode(':', \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions'])->getKeys());
    $this->renderer->renderRoot($build);
    $this->assertNotEmpty($this->container->get('cache.render')->get($cid), 'The block render element has been cached.');

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

    // 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']);
    // Re-add the block because \Drupal\block\BlockViewBuilder::buildBlock()
'#element' => 4,
      ],
    ];

    return $build;
  }

  /** * #pre_render callback for #type => pager that shows the pager cache context. */
  public static function showPagerCacheContext(array $pager) {
    \Drupal::messenger()->addStatus(\Drupal::service('cache_contexts_manager')->convertTokensToKeys(['url.query_args.pagers:' . $pager['#element']])->getKeys()[0]);
    return $pager;
  }

  /** * {@inheritdoc} */
  public static function trustedCallbacks() {
    return ['showPagerCacheContext'];
  }

}
    // context.     $this->drupalCreateContentType(['type' => 'page']);
    $node = $this->createNode();

    // Get a fully built entity view render array.     $build = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'full');

    // Render it so the default cache contexts are applied.     $renderer->renderRoot($build);
    $this->assertContains('workspace', $build['#cache']['contexts']);

    $cid_parts = array_merge($build['#cache']['keys']$cache_contexts_manager->convertTokensToKeys($build['#cache']['contexts'])->getKeys());
    $this->assertContains('[workspace]=live', $cid_parts);

    // Test that a cache entry is created.     $cid = implode(':', $cid_parts);
    $bin = $build['#cache']['bin'];
    $this->assertInstanceOf(\stdClass::class$this->container->get('cache.' . $bin)->get($cid));

    // Switch to the 'stage' workspace and check that the correct workspace     // cache context is used.     $test_user = $this->drupalCreateUser(['view any workspace']);
    $this->drupalLogin($test_user);

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