setCacheTags example

/** * Applies the cacheability of the current display to the given render array. * * @param array $element * The render array with updated cacheability metadata. */
  protected function applyDisplayCacheabilityMetadata(array &$element) {
    /** @var \Drupal\views\Plugin\views\cache\CachePluginBase $cache */
    $cache = $this->getPlugin('cache');

    (new CacheableMetadata())
      ->setCacheTags(Cache::mergeTags($this->view->getCacheTags()$this->display['cache_metadata']['tags'] ?? []))
      ->setCacheContexts($this->display['cache_metadata']['contexts'] ?? [])
      ->setCacheMaxAge(Cache::mergeMaxAges($cache->getCacheMaxAge()$this->display['cache_metadata']['max-age'] ?? Cache::PERMANENT))
      ->merge(CacheableMetadata::createFromRenderArray($element))
      ->applyTo($element);
  }

  /** * {@inheritdoc} */
  public function elementPreRender(array $element) {
    $view = $element['#view'];
    
$request = Request::create('/');
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));
    $request_stack->push($request);
    $request_context->fromRequest($request);

    $menu_tree = \Drupal::menuTree();
    $renderer = \Drupal::service('renderer');

    $default_menu_cacheability = (new BubbleableMetadata())
      ->setCacheMaxAge(Cache::PERMANENT)
      ->setCacheTags(['config:system.menu.tools'])
      ->setCacheContexts(['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions']);

    User::create(['uid' => 1, 'name' => $this->randomString()])->save();
    User::create(['uid' => 2, 'name' => $this->randomString()])->save();

    // Five test cases, four asserting one outbound path/route processor, and     // together covering one of each:     // - no cacheability metadata,     // - a cache context,     // - a cache tag,     // - a cache max-age.
return NestedArray::mergeDeep(['data' => ['id' => $this->entity->uuid()]]$this->getPostDocument());
  }

  /** * Returns the expected cacheability for an unauthorized response. * * @return \Drupal\Core\Cache\CacheableMetadata * The expected cacheability. */
  protected function getExpectedUnauthorizedAccessCacheability() {
    return (new CacheableMetadata())
      ->setCacheTags(['4xx-response', 'http_response'])
      ->setCacheContexts(['url.site', 'user.permissions'])
      ->addCacheContexts($this->entity->getEntityType()->isRevisionable()
        ? ['url.query_args:resourceVersion']
        : []
      );
  }

  /** * The expected cache tags for the GET/HEAD response of the test entity. * * @param array|null $sparse_fieldset * If a sparse fieldset is being requested, limit the expected cache tags * for this entity's fields to just these fields. * * @return string[] * A set of cache tags. * * @see ::testGetIndividual() */
return 'menu_trail.' . $menu_name . '|' . implode('|', $active_trail);
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata($menu_name = NULL) {
    if (!$menu_name) {
      throw new \LogicException('No menu name provided for menu.active_trails cache context.');
    }
    $cacheable_metadata = new CacheableMetadata();
    return $cacheable_metadata->setCacheTags(["config:system.menu.$menu_name"]);
  }

}
return parent::getExpectedUnauthorizedAccessMessage($method);
    }
  }

  /** * {@inheritdoc} * * @todo Fix this in https://www.drupal.org/node/2820315. */
  protected function getExpectedUnauthorizedAccessCacheability() {
    return (new CacheableMetadata())
      ->setCacheTags(['4xx-response', 'http_response'])
      ->setCacheContexts(['user.roles']);
  }

  /** * {@inheritdoc} */
  protected function getExpectedUnauthorizedEntityAccessCacheability($is_authenticated) {
    // @see \Drupal\block\BlockAccessControlHandler::checkAccess()     return parent::getExpectedUnauthorizedEntityAccessCacheability($is_authenticated)
      ->addCacheTags([
        'config:block.block.llama',
        
$this->assertEqualsCanonicalizing($expected_cacheability->getCacheContexts()$result->getCacheContexts());
    $this->assertSame($expected_cacheability->getCacheMaxAge()$result->getCacheMaxAge());
    $this->assertSame(['library']array_keys($result->getAttachments()));
    $this->assertSame(['media/filter.caption']$result->getAttachments()['library']);
  }

  /** * Data provider for testBasics(). */
  public function providerTestBasics() {
    $default_cacheability = (new CacheableMetadata())
      ->setCacheTags([
        '_media_test_embed_filter_access:media:1',
        '_media_test_embed_filter_access:user:2',
        'config:image.style.thumbnail',
        'file:1',
        'media:1',
        'media_view',
        'user:2',
      ])
      ->setCacheContexts(['timezone', 'user.permissions'])
      ->setCacheMaxAge(Cache::PERMANENT);

    


    // The 'user.permissions' cache context ensures that if the permissions for     // a role are modified, users are not served stale render cache content.     // But, when entire responses are cached in reverse proxies, the value for     // the cache context is never calculated, causing the stale response to not     // be invalidated. Therefore, when varying by permissions and the current     // user is the anonymous user, also add the cache tag for the 'anonymous'     // role.     if (in_array('user.permissions', $response->getCacheableMetadata()->getCacheContexts())) {
      $per_permissions_response_for_anon = new CacheableMetadata();
      $per_permissions_response_for_anon->setCacheTags(['config:user.role.anonymous']);
      $response->addCacheableDependency($per_permissions_response_for_anon);
    }
  }

  /** * Registers the methods in this class that should be listeners. * * @return array * An array of event listener definitions. */
  public static function getSubscribedEvents(): array {
    
public function createConfigObject($name$collection = StorageInterface::DEFAULT_COLLECTION) {
    return NULL;
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata($name) {
    $metadata = new CacheableMetadata();
    $metadata
      ->setCacheContexts(['pirate_day'])
      ->setCacheTags(['pirate-day-tag'])
      ->setCacheMaxAge(PirateDayCacheContext::PIRATE_DAY_MAX_AGE);
    return $metadata;
  }

}

  public function getCacheableMetadata($operation = NULL) {
    $cacheable_metadata = new CacheableMetadata();

    if (!\Drupal::moduleHandler()->hasImplementations('node_grants')) {
      return $cacheable_metadata;
    }

    // The node grants may change if the user is updated. (The max-age is set to     // zero below, but sites may override this cache context, and change it to a     // non-zero value. In such cases, this cache tag is needed for correctness.)     $cacheable_metadata->setCacheTags(['user:' . $this->user->id()]);

    // If the site is using node grants, this cache context can not be     // optimized.     return $cacheable_metadata->setCacheMaxAge(0);
  }

}
default:
        return parent::getExpectedUnauthorizedAccessMessage($method);
    }
  }

  /** * {@inheritdoc} */
  protected function getExpectedUnauthorizedAccessCacheability() {
    // @see \Drupal\block\BlockAccessControlHandler::checkAccess()     return parent::getExpectedUnauthorizedAccessCacheability()
      ->setCacheTags([
        '4xx-response',
        'config:block.block.llama',
        'http_response',
        'user:2',
      ])
      ->setCacheContexts(['url.site', 'user.roles']);
  }

  /** * {@inheritdoc} */
  
return implode(',', $this->user->getRoles());
    }
    else {
      return (in_array($role$this->user->getRoles()) ? '0' : '1');
    }
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata($role = NULL) {
    return (new CacheableMetadata())->setCacheTags(['user:' . $this->user->id()]);
  }

}
      // original config object would remain present, which would be wrong.       // 2. Some Config entities choose to not use the cache tag that the under-       // lying Config object provides by default (For performance and       // cacheability reasons it may not make sense to have a unique cache       // tag for every Config entity. The DateFormat Config entity specifies       // the 'rendered' cache tag for example, because A) date formats are       // changed extremely rarely, so invalidating all render cache items is       // fine, B) it means fewer cache tags per page.).       // 3. Fewer cache tags is better for performance.       $self_referring_cache_tag = ['config:' . $configs[$id]->getName()];
      $config_cacheability = CacheableMetadata::createFromObject($configs[$id]);
      $config_cacheability->setCacheTags(array_diff($config_cacheability->getCacheTags()$self_referring_cache_tag));
      $entity->addCacheableDependency($config_cacheability);
    }

    return $entities;
  }

  /** * {@inheritdoc} */
  protected function doCreate(array $values) {
    // Set default language to current language if not provided.
use ComputedItemListTrait;

  /** * {@inheritdoc} */
  protected function computeValue() {
    /** @var \Drupal\entity_test\Plugin\Field\FieldType\ComputedTestCacheableStringItem $item */
    $item = $this->createItem(0, 'computed test cacheable string field');
    $cacheability = (new CacheableMetadata())
      ->setCacheContexts(['url.query_args:computed_test_cacheable_string_field'])
      ->setCacheTags(['field:computed_test_cacheable_string_field'])
      ->setCacheMaxAge(800);
    $item->get('value')->addCacheableDependency($cacheability);
    $this->list[0] = $item;
  }

}

  public function providerTestMerge() {
    return [
      // All empty.       [(new CacheableMetadata())(new CacheableMetadata())(new CacheableMetadata())],
      // Cache contexts.       [(new CacheableMetadata())->setCacheContexts(['foo'])(new CacheableMetadata())->setCacheContexts(['bar'])(new CacheableMetadata())->setCacheContexts(['bar', 'foo'])],
      // Cache tags.       [(new CacheableMetadata())->setCacheTags(['foo'])(new CacheableMetadata())->setCacheTags(['bar'])(new CacheableMetadata())->setCacheTags(['foo', 'bar'])],
      // Cache max-ages.       [(new CacheableMetadata())->setCacheMaxAge(60)(new CacheableMetadata())->setCacheMaxAge(Cache::PERMANENT)(new CacheableMetadata())->setCacheMaxAge(60)],
    ];
  }

  /** * This delegates to Cache::mergeTags(), so just a basic test. * * @covers ::addCacheTags */
  public function testAddCacheTags() {
    
// @see \Drupal\Core\EventSubscriber\AnonymousUserResponseSubscriber::onRespond()         ->addCacheableDependency($this->getExpectedUnauthorizedEntityAccessCacheability(FALSE));
      // - \Drupal\Core\EventSubscriber\AnonymousUserResponseSubscriber applies       // to cacheable anonymous responses: it updates their cacheability.       // - A 403 response to a GET request is cacheable.       // Therefore we must update our cacheability expectations accordingly.       if (in_array('user.permissions', $expected_cookie_403_cacheability->getCacheContexts(), TRUE)) {
        $expected_cookie_403_cacheability->addCacheTags(['config:user.role.anonymous']);
      }
      // @todo Fix \Drupal\block\BlockAccessControlHandler::mergeCacheabilityFromConditions() in https://www.drupal.org/node/2867881       if (static::$entityTypeId === 'block') {
        $expected_cookie_403_cacheability->setCacheTags(str_replace('user:2', 'user:0', $expected_cookie_403_cacheability->getCacheTags()));
      }
      $this->assertResourceErrorResponse(403, FALSE, $response$expected_cookie_403_cacheability->getCacheTags()$expected_cookie_403_cacheability->getCacheContexts(), 'MISS', FALSE);
    }
    else {
      $this->assertResourceErrorResponse(403, FALSE, $response);
    }
  }

  /** * {@inheritdoc} */
  
Home | Imprint | This part of the site doesn't use cookies.