CacheableMetadata example

$route_names[] = $plugin->getRouteName();
          $this->instances[$route_appears][$plugin_id] = $plugin;
        }
      }
      // Pre-fetch all the action route objects. This reduces the number of SQL       // queries that would otherwise be triggered by the access manager.       if (!empty($route_names)) {
        $this->routeProvider->getRoutesByNames($route_names);
      }
    }
    $links = [];
    $cacheability = new CacheableMetadata();
    $cacheability->addCacheContexts(['route']);
    /** @var \Drupal\Core\Menu\LocalActionInterface $plugin */
    foreach ($this->instances[$route_appears] as $plugin_id => $plugin) {
      $route_name = $plugin->getRouteName();
      $route_parameters = $plugin->getRouteParameters($this->routeMatch);
      $access = $this->accessManager->checkNamedRoute($route_name$route_parameters$this->account, TRUE);
      $links[$plugin_id] = [
        '#theme' => 'menu_local_action',
        '#link' => [
          'title' => $this->getTitle($plugin),
          'url' => Url::fromRoute($route_name$route_parameters),
          
    if (is_array($result) && ($request->query->has(static::WRAPPER_FORMAT) || $request->getRequestFormat() == 'html')) {
      $wrapper = $request->query->get(static::WRAPPER_FORMAT, 'html');

      // Fall back to HTML if the requested wrapper envelope is not available.       $wrapper = isset($this->mainContentRenderers[$wrapper]) ? $wrapper : 'html';

      $renderer = $this->classResolver->getInstanceFromDefinition($this->mainContentRenderers[$wrapper]);
      $response = $renderer->renderResponse($result$request$this->routeMatch);
      // The main content render array is rendered into a different Response       // object, depending on the specified wrapper format.       if ($response instanceof CacheableResponseInterface) {
        $main_content_view_subscriber_cacheability = (new CacheableMetadata())->setCacheContexts(['url.query_args:' . static::WRAPPER_FORMAT]);
        $response->addCacheableDependency($main_content_view_subscriber_cacheability);
      }
      $event->setResponse($response);
    }
  }

  /** * {@inheritdoc} */
  public static function getSubscribedEvents(): array {
    $events[KernelEvents::VIEW][] = ['onViewRenderArray'];

    
/** * Creates a CacheableNormalization instance without any special cacheability. * * @param array|string|int|float|bool|null $normalization * The normalized data. This value must not contain any * CacheableNormalizations. * * @return static * The CacheableNormalization. */
  public static function permanent($normalization) {
    return new static(new CacheableMetadata()$normalization);
  }

  /** * Gets the decorated normalization. * * @return array|string|int|float|bool|null * The normalization. */
  public function getNormalization() {
    return $this->normalization;
  }

  

  public function getContext() {
    $request = $this->requestStack->getCurrentRequest();
    return $request->getSchemeAndHttpHost() . $request->getBaseUrl();
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

}
/** * {@inheritdoc} */
  public function createConfigObject($name$collection = StorageInterface::DEFAULT_COLLECTION) {
    return NULL;
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata($name) {
    return new CacheableMetadata();
  }

}

  public function getContext() {
    // date_default_timezone_set() is called in AccountProxy::setAccount(), so     // we can safely retrieve the timezone.     return date_default_timezone_get();
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

}
protected static function buildLinkCollectionFromEntityReferenceField(ResourceObject $context, EntityReferenceFieldItemListInterface $field, LinkCollection $links) {
    $context_resource_type = $context->getResourceType();
    $public_field_name = $context_resource_type->getPublicName($field->getName());
    if ($context_resource_type->isLocatable() && !$context_resource_type->isInternal()) {
      $context_is_versionable = $context_resource_type->isVersionable();
      if (!$links->hasLinkWithKey('self')) {
        $route_name = Routes::getRouteName($context_resource_type, "$public_field_name.relationship.get");
        $self_link = Url::fromRoute($route_name['entity' => $context->getId()]);
        if ($context_is_versionable) {
          $self_link->setOption('query', [JsonApiSpec::VERSION_QUERY_PARAMETER => $context->getVersionIdentifier()]);
        }
        $links = $links->withLink('self', new Link(new CacheableMetadata()$self_link, 'self'));
      }
      $has_non_internal_resource_type = array_reduce($context_resource_type->getRelatableResourceTypesByField($public_field_name)function D$carry, ResourceType $target) {
        return $carry ?: !$target->isInternal();
      }, FALSE);
      // If a `related` link was not provided, automatically generate one from       // the relationship object to the collection resource with all of the       // resources targeted by this relationship. However, that link should       // *not* be generated if all of the relatable resources are internal.       // That's because, in that case, a route will not exist for it.       if (!$links->hasLinkWithKey('related') && $has_non_internal_resource_type) {
        $route_name = Routes::getRouteName($context_resource_type, "$public_field_name.related");
        

  protected static function toCollectionResourceResponse(array $responses$self_link$is_multiple) {
    assert(count($responses) > 0);
    $merged_document = [];
    $merged_cacheability = new CacheableMetadata();
    foreach ($responses as $response) {
      $response_document = $response->getResponseData();
      // If any of the response documents had top-level errors, we should later       // expect the merged document to have all errors as omitted links under       // the 'meta.omitted' member.       if (!empty($response_document['errors'])) {
        static::addOmittedObject($merged_documentstatic::errorsToOmittedObject($response_document['errors']));
      }
      if (!empty($response_document['meta']['omitted'])) {
        static::addOmittedObject($merged_document$response_document['meta']['omitted']);
      }
      
/** * {@inheritdoc} */
  public function getContext() {
    return $this->requestStack->getCurrentRequest()->getUri();
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

}

  protected function buildSections(FieldableEntityInterface $entity) {
    $contexts = $this->getContextsForEntity($entity);
    // @todo Remove in https://www.drupal.org/project/drupal/issues/3018782.     $label = new TranslatableMarkup('@entity being viewed', [
      '@entity' => $entity->getEntityType()->getSingularLabel(),
    ]);
    $contexts['layout_builder.entity'] = EntityContext::fromEntity($entity$label);

    $cacheability = new CacheableMetadata();
    $storage = $this->sectionStorageManager()->findByContext($contexts$cacheability);

    $build = [];
    if ($storage) {
      foreach ($storage->getSections() as $delta => $section) {
        $build[$delta] = $section->toRenderArray($contexts);
      }
    }
    // The render array is built based on decisions made by @SectionStorage     // plugins and therefore it needs to depend on the accumulated     // cacheability of those decisions.
default:
        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([
        
// Default to the 'disabled' state.     $state = \Drupal::state()->get('config_override_integration_test.enabled', FALSE) ? 'yes' : 'no';
    return 'config_override_integration_test.' . $state;
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata() {
    // Since this depends on State this can change at any time and is not     // cacheable.     $metadata = new CacheableMetadata();
    $metadata->setCacheMaxAge(0);
    return $metadata;
  }

}
/** * {@inheritdoc} */
  public function getContext() {
    return $this->requestStack->getCurrentRequest()->getProtocolVersion();
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

}
/** * Test the cacheability of the linkset endpoint. * * This test's purpose is to ensure that the menu linkset response is properly * cached. It does this by sending a request and validating it has a cache * miss and the correct cacheability meta, then by sending the same request to * assert a cache hit. Finally, a new menu item is created to ensure that the * cached response is properly invalidated. */
  public function testCacheability() {
    $this->enableEndpoint(TRUE);
    $expected_cacheability = new CacheableMetadata();
    $expected_cacheability->addCacheContexts([
      'user.permissions',
    ]);
    $expected_cacheability->addCacheTags([
      'config:system.menu.main',
      'config:user.role.anonymous',
      'http_response',
      'node:1',
      'node:2',
      'node:3',
    ]);
    
/** * {@inheritdoc} */
  protected function getExpectedUnauthorizedAccessMessage($method) {
    return '';
  }

  /** * {@inheritdoc} */
  protected function getExpectedUnauthorizedAccessCacheability() {
    return new CacheableMetadata();
  }

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