addCacheTags example

'DELETE' => "The following permissions are required: 'access block library' AND 'delete any basic block content'.",
      default => parent::getExpectedUnauthorizedAccessMessage($method),
    };
  }

  /** * {@inheritdoc} */
  protected function getExpectedUnauthorizedEntityAccessCacheability($is_authenticated) {
    // @see \Drupal\block_content\BlockContentAccessControlHandler()     return parent::getExpectedUnauthorizedEntityAccessCacheability($is_authenticated)
      ->addCacheTags(['block_content:1']);
  }

  /** * {@inheritdoc} */
  protected function getExpectedCacheTags() {
    return Cache::mergeTags(parent::getExpectedCacheTags()['config:filter.format.plain_text']);
  }

  /** * {@inheritdoc} */
    // response passed to TrustedRedirectResponse::createFromRedirectResponse()     // is itself cacheable.     $expected_cacheability = ($redirect_response instanceof CacheableResponseInterface) ? $redirect_response->getCacheableMetadata() : (new CacheableMetadata())->setCacheMaxAge(0);
    $this->assertEquals($expected_cacheability$trusted_redirect_response->getCacheableMetadata());
  }

  /** * @return array */
  public function providerCreateFromRedirectResponse() {
    return [
      'cacheable-with-tags' => [(new CacheableRedirectResponse('/example'))->addCacheableDependency((new CacheableMetadata())->addCacheTags(['foo']))],
      'cacheable-with-max-age-0' => [(new CacheableRedirectResponse('/example'))->addCacheableDependency((new CacheableMetadata())->setCacheMaxAge(0))],
      'uncacheable' => [new RedirectResponse('/example')],
    ];
  }

}
/** * {@inheritdoc} */
  public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    // Rewrite user/uid to user/username.     if (preg_match('!^/user/([0-9]+)(/.*)?!', $path$matches)) {
      if ($account = User::load($matches[1])) {
        $matches += [2 => ''];
        $path = '/user/' . $account->getAccountName() . $matches[2];
        if ($bubbleable_metadata) {
          $bubbleable_metadata->addCacheTags($account->getCacheTags());
        }
      }
    }

    // Verify that $options are alterable.     if ($path == '/user/login') {
      $options['query']['foo'] = 'bar';
    }

    return $path;
  }

}
public function __construct(AccountInterface $current_user) {
    $this->currentUser = $current_user;
  }

  /** * {@inheritdoc} */
  public function normalize($object$format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
    $cacheability = new CacheableMetadata();
    $cacheability->addCacheableDependency($object);

    $cacheability->addCacheTags(['config:system.logging']);
    if (\Drupal::config('system.logging')->get('error_level') === ERROR_REPORTING_DISPLAY_VERBOSE) {
      $cacheability->setCacheMaxAge(0);
    }

    return new HttpExceptionNormalizerValue($cacheabilitystatic::rasterizeValueRecursive($this->buildErrorObjects($object)));
  }

  /** * Builds the normalized JSON:API error objects for the response. * * @param \Symfony\Component\HttpKernel\Exception\HttpException $exception * The Exception. * * @return array * The error objects to include in the response. */
if ($config->get('fast_404.enabled') && $exclude_paths && !preg_match($exclude_paths$request->getPathInfo())) {
      $fast_paths = $config->get('fast_404.paths');
      if ($fast_paths && preg_match($fast_paths$request->getPathInfo())) {
        $fast_404_html = strtr($config->get('fast_404.html')['@path' => Html::escape($request->getUri())]);
        $response = new HtmlResponse($fast_404_html, Response::HTTP_NOT_FOUND);
        // Some routes such as system.files conditionally throw a         // NotFoundHttpException depending on URL parameters instead of just the         // route and route parameters, so add the URL cache context to account         // for this.         $cacheable_metadata = new CacheableMetadata();
        $cacheable_metadata->setCacheContexts(['url']);
        $cacheable_metadata->addCacheTags(['4xx-response']);
        $response->addCacheableDependency($cacheable_metadata);
        $event->setResponse($response);
      }
    }
  }

  /** * Invalidates 4xx-response cache tag if fast 404 config is changed. * * @param \Drupal\Core\Config\ConfigCrudEvent $event * The configuration event. */
'related' => [
            'href' => $expected_base_url->toString() . '/field_jsonapi_test_entity_ref' . $version_query_string,
          ],
          'self' => [
            'href' => $expected_base_url->toString() . '/relationships/field_jsonapi_test_entity_ref' . $version_query_string,
          ],
        ],
      ];
    }

    $basic_cacheability = (new CacheableMetadata())
      ->addCacheTags($this->getExpectedCacheTags())
      ->addCacheContexts($this->getExpectedCacheContexts());
    return static::decorateExpectedResponseForIncludedFields(new CacheableResourceResponse($individual_document)$resource_data['responses'])
      ->addCacheableDependency($basic_cacheability);
  }

  /** * Maps an array of PSR responses to JSON:API ResourceResponses. * * @param \Psr\Http\Message\ResponseInterface[] $responses * The PSR responses to be mapped. * * @return \Drupal\jsonapi\ResourceResponse[] * The ResourceResponses. */
$this->t('Status'),
        $this->t('Operations'),
      ];
    }

    $build['#title'] = $this->t('Translations of %label', ['%label' => $entity->label() ?? $entity->id()]);

    // Add metadata to the build render array to let other modules know about     // which entity this is.     $build['#entity'] = $entity;
    $cacheability
      ->addCacheTags($entity->getCacheTags())
      ->applyTo($build);

    $build['content_translation_overview'] = [
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $rows,
    ];

    return $build;
  }

  
'nested_empty_fieldset',
      'nested_fieldset_with_owner_fieldset',
    ]));
  }

  /** * {@inheritdoc} */
  protected static function getExpectedCollectionCacheability(AccountInterface $account, array $collection, array $sparse_fieldset = NULL, $filtered = FALSE) {
    $cacheability = parent::getExpectedCollectionCacheability($account$collection$sparse_fieldset$filtered);
    if ($filtered) {
      $cacheability->addCacheTags(['state:jsonapi__entity_test_filter_access_blacklist']);
    }
    return $cacheability;
  }

}

      ],
    ];
  }

  /** * {@inheritdoc} */
  protected function getExpectedUnauthorizedEntityAccessCacheability($is_authenticated) {
    // @see \Drupal\media\MediaAccessControlHandler::checkAccess()     return parent::getExpectedUnauthorizedEntityAccessCacheability($is_authenticated)
      ->addCacheTags(['media:1']);
  }

}
class TestPageDisplayVariantSubscriber implements EventSubscriberInterface {

  /** * Selects the page display variant. * * @param \Drupal\Core\Render\PageDisplayVariantSelectionEvent $event * The event to process. */
  public function onSelectPageDisplayVariant(PageDisplayVariantSelectionEvent $event) {
    $event->setPluginId('display_variant_test');
    $event->setPluginConfiguration(['required_configuration' => 'A very important, required value.']);
    $event->addCacheTags(['custom_cache_tag']);

    $context = new Context(new ContextDefinition('string', NULL, TRUE), 'Explicitly passed in context.');
    $event->setContexts(['context' => $context]);
  }

  /** * {@inheritdoc} */
  public static function getSubscribedEvents(): array {
    $events[RenderEvents::SELECT_PAGE_DISPLAY_VARIANT][] = ['onSelectPageDisplayVariant'];
    return $events;
  }
$loader = new FilesystemLoader();
    $twig = new Environment($loader[
      'debug' => TRUE,
      'cache' => FALSE,
      'autoescape' => 'html',
      'optimizations' => 0,
    ]);

    $twig->addExtension($this->systemUnderTest);
    $link = new GeneratedLink();
    $link->setGeneratedLink('<a href="http://example.com"></a>');
    $link->addCacheTags(['foo']);
    $link->addAttachments(['library' => ['system/base']]);

    $this->renderer->expects($this->atLeastOnce())
      ->method('render')
      ->with([
        "#cache" => [
          "contexts" => [],
          "tags" => ["foo"],
          "max-age" => -1,
        ],
        "#attached" => ['library' => ['system/base']],
      ]);
/** * {@inheritdoc} */
  public function getCacheTagsToInvalidate() {
    return $this->storage->getCacheTagsToInvalidate();
  }

  /** * {@inheritdoc} */
  public function addCacheTags(array $cache_tags) {
    return $this->storage->addCacheTags($cache_tags);
  }

  /** * Gets the lock on this View. * * @return \Drupal\Core\TempStore\Lock|null * The lock, if one exists. */
  public function getLock() {
    return $this->lock;
  }

  

  public function getContext() {
    return 'is_front.' . (int) $this->pathMatcher->isFrontPage();
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata() {
    $metadata = new CacheableMetadata();
    $metadata->addCacheTags(['config:system.site']);
    return $metadata;
  }

}
/** * Sets extra headers on any responses, also subrequest ones. * * @param \Symfony\Component\HttpKernel\Event\ResponseEvent $event * The event to process. */
  public function onAllResponds(ResponseEvent $event) {
    $response = $event->getResponse();
    // Always add the 'http_response' cache tag to be able to invalidate every     // response, for example after rebuilding routes.     if ($response instanceof CacheableResponseInterface) {
      $response->getCacheableMetadata()->addCacheTags(['http_response']);
    }
  }

  /** * Sets extra headers on successful responses. * * @param \Symfony\Component\HttpKernel\Event\ResponseEvent $event * The event to process. */
  public function onRespond(ResponseEvent $event) {
    if (!$event->isMainRequest()) {
      
$cache_contexts_manager->reveal();
    $c->set('cache_contexts_manager', $cache_contexts_manager);
    \Drupal::setContainer($c);

    return [
      'permissionless + unlocked' => [
        'permissionless',
        'unlocked',
        AccessResult::allowed(),
        AccessResult::neutral()->addCacheContexts(['user.permissions'])->setReason("The 'administer menu' permission is required."),
        AccessResult::neutral()->addCacheContexts(['user.permissions'])->setReason("The 'administer menu' permission is required."),
        AccessResult::neutral()->addCacheContexts(['user.permissions'])->setReason("The 'administer menu' permission is required.")->addCacheTags(['config:system.menu.llama']),
        AccessResult::neutral()->addCacheContexts(['user.permissions'])->setReason("The 'administer menu' permission is required."),
      ],
      'permissionless + locked' => [
        'permissionless',
        'locked',
        AccessResult::allowed(),
        AccessResult::neutral()->addCacheContexts(['user.permissions'])->setReason("The 'administer menu' permission is required."),
        AccessResult::neutral()->addCacheContexts(['user.permissions'])->setReason("The 'administer menu' permission is required."),
        AccessResult::forbidden()->addCacheTags(['config:system.menu.llama'])->setReason("The Menu config entity is locked."),
        AccessResult::neutral()->addCacheContexts(['user.permissions'])->setReason("The 'administer menu' permission is required."),
      ],
      
Home | Imprint | This part of the site doesn't use cookies.