addCacheContexts example


class FilterTestCacheContexts extends FilterBase {

  /** * {@inheritdoc} */
  public function process($text$langcode) {
    $result = new FilterProcessResult($text);
    // The changes made by this filter are language-specific.     $result->addCacheContexts(['languages:' . LanguageInterface::TYPE_CONTENT]);
    return $result;
  }

}

  public function access(Route $route, AccountInterface $account) {
    // Requirements just allow strings, so this might be a comma separated list.     $rid_string = $route->getRequirement('_role');

    $explode_and = array_filter(array_map('trim', explode(',', $rid_string)));
    if (count($explode_and) > 1) {
      $diff = array_diff($explode_and$account->getRoles());
      if (empty($diff)) {
        return AccessResult::allowed()->addCacheContexts(['user.roles']);
      }
    }
    else {
      $explode_or = array_filter(array_map('trim', explode('+', $rid_string)));
      $intersection = array_intersect($explode_or$account->getRoles());
      if (!empty($intersection)) {
        return AccessResult::allowed()->addCacheContexts(['user.roles']);
      }
    }

    // If there is no allowed role, give other access checks a chance.
$expected_page_cache_header_value = $method === 'GET' ? 'MISS' : FALSE;
    $expected_cacheability = $this->getExpectedUnauthorizedAccessCacheability()
      ->addCacheableDependency($this->getExpectedUnauthorizedEntityAccessCacheability(FALSE))
      // @see \Drupal\basic_auth\Authentication\Provider\BasicAuth::challengeException()       ->addCacheableDependency($this->config('system.site'))
      // @see \Drupal\Core\EventSubscriber\AnonymousUserResponseSubscriber::onRespond()       ->addCacheTags(['config:user.role.anonymous']);
    // Only add the 'user.roles:anonymous' cache context if its parent cache     // context is not already present.     if (!in_array('user.roles', $expected_cacheability->getCacheContexts(), TRUE)) {
      $expected_cacheability->addCacheContexts(['user.roles:anonymous']);
    }
    $this->assertResourceErrorResponse(401, 'No authentication credentials provided.', $response$expected_cacheability->getCacheTags()$expected_cacheability->getCacheContexts()$expected_page_cache_header_value, FALSE);
  }

  /** * {@inheritdoc} */
  protected function assertAuthenticationEdgeCases($method, Url $url, array $request_options) {
  }

}
if (!isset($options['query'][$this->queryParam])) {
          $options['query'][$this->queryParam] = $this->queryValue;
        }
        if ($bubbleable_metadata) {
          // Cached URLs that have been processed by this outbound path           // processor must be:           $bubbleable_metadata
            // - invalidated when the language negotiation config changes, since             // another query parameter may be used to determine the language.             ->addCacheTags($this->config->get('language.negotiation')->getCacheTags())
            // - varied by the configured query parameter.             ->addCacheContexts(['url.query_args:' . $this->queryParam]);
        }
      }
    }
    return $path;
  }

  /** * {@inheritdoc} */
  public function getLanguageSwitchLinks(Request $request$type, Url $url) {
    $links = [];
    
$options['absolute'] = TRUE;
        }
        else {
          $base = str_replace('https://', 'http://', $current_base_url);
          $options['absolute'] = TRUE;
        }
      }
      else {
        $base = $current_base_url;
      }
      if ($collect_bubbleable_metadata) {
        $generated_url->addCacheContexts(['url.site']);
      }
    }
    else {
      $base = $current_base_path;
    }

    $prefix = empty($uri) ? rtrim($options['prefix'], '/') : $options['prefix'];

    $uri = str_replace('%2F', '/', rawurlencode($prefix . $uri));
    $query = $options['query'] ? ('?' . UrlHelper::buildQuery($options['query'])) : '';
    $url = $base . $options['script'] . $uri . $query . $options['fragment'];
    

trait RefinableCacheableDependencyTrait {

  use CacheableDependencyTrait;

  /** * {@inheritdoc} */
  public function addCacheableDependency($other_object) {
    if ($other_object instanceof CacheableDependencyInterface) {
      $this->addCacheContexts($other_object->getCacheContexts());
      $this->addCacheTags($other_object->getCacheTags());
      $this->mergeCacheMaxAge($other_object->getCacheMaxAge());
    }
    else {
      // Not a cacheable dependency, this can not be cached.       $this->cacheMaxAge = 0;
    }
    return $this;
  }

  /** * {@inheritdoc} */
if (count($grants) > 0) {
      $query->condition($grants);
    }

    // Only the 'view' node grant can currently be cached; the others currently     // don't have any cacheability metadata. Hopefully, we can add that in the     // future, which would allow this access check result to be cacheable in all     // cases. For now, this must remain marked as uncacheable, even when it is     // theoretically cacheable, because we don't have the necessary metadata to     // know it for a fact.     $set_cacheability = function DAccessResult $access_result) use ($operation) {
      $access_result->addCacheContexts(['user.node_grants:' . $operation]);
      if ($operation !== 'view') {
        $access_result->setCacheMaxAge(0);
      }
      return $access_result;
    };

    if ($query->execute()->fetchField()) {
      return $set_cacheability(AccessResult::allowed());
    }
    else {
      return $set_cacheability(AccessResult::neutral());
    }
if ($scheme_req && ($req = $scheme_req[0]) && $scheme !== $req) {
      $scheme = $req;
    }
    $port = '';
    if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
      $port = ':' . $this->context->getHttpPort();
    }
    elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
      $port = ':' . $this->context->getHttpsPort();
    }
    if ($collect_bubbleable_metadata) {
      $generated_url->addCacheContexts(['url.site']);
    }
    $url = $scheme . '://' . $host . $port . $base_url . $path . $query . $fragment;
    return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
  }

  /** * Passes the path to a processor manager to allow alterations. */
  protected function processPath($path, &$options = [], BubbleableMetadata $bubbleable_metadata = NULL) {
    $actual_path = $path === '/' ? $path : rtrim($path, '/');
    return $this->pathProcessor->processOutbound($actual_path$options$this->requestStack->getCurrentRequest()$bubbleable_metadata);
  }
$this->assertEquals(10, $bubbleable_metadata->getCacheMaxAge());
  }

  /** * @covers ::replace */
  public function testReplaceWithHookTokensWithBubbleableMetadata() {
    $this->moduleHandler->expects($this->any())
      ->method('invokeAll')
      ->willReturnCallback(function D$hook_name$args) {
        $cacheable_metadata = $args[4];
        $cacheable_metadata->addCacheContexts(['custom_context']);
        $cacheable_metadata->addCacheTags(['node:1']);
        $cacheable_metadata->setCacheMaxAge(10);

        return ['[node:title]' => 'hello world'];
      });

    $node = $this->prophesize('Drupal\node\NodeInterface');
    $node->getCacheContexts()->willReturn([]);
    $node->getCacheTags()->willReturn([]);
    $node->getCacheMaxAge()->willReturn(14);
    $node = $node->reveal();

    
$this->assertEquals([]$breadcrumb->getCacheTags());
    $this->assertEquals(Cache::PERMANENT, $breadcrumb->getCacheMaxAge());
  }

  /** * Tests the build method with a single breadcrumb builder. */
  public function testBuildWithSingleBuilder() {
    $builder = $this->createMock('Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface');
    $links = ['<a href="/example">Test</a>'];
    $this->breadcrumb->setLinks($links);
    $this->breadcrumb->addCacheContexts(['foo'])->addCacheTags(['bar']);

    $builder->expects($this->once())
      ->method('applies')
      ->willReturn(TRUE);

    $builder->expects($this->once())
      ->method('build')
      ->willReturn($this->breadcrumb);

    $route_match = $this->createMock('Drupal\Core\Routing\RouteMatchInterface');
    $this->moduleHandler->expects($this->once())
      

  public function applies(RouteMatchInterface $route_match) {
    return $route_match->getRouteName() == 'forum.page' && $route_match->getParameter('taxonomy_term');
  }

  /** * {@inheritdoc} */
  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = parent::build($route_match);
    $breadcrumb->addCacheContexts(['route']);

    // Add all parent forums to breadcrumbs.     /** @var \Drupal\taxonomy\TermInterface $term */
    $term = $route_match->getParameter('taxonomy_term');
    $term_id = $term->id();
    $breadcrumb->addCacheableDependency($term);

    $parents = $this->termStorage->loadAllParents($term_id);
    if ($parents) {
      foreach (array_reverse($parents) as $parent) {
        if ($parent->id() != $term_id) {
          
$entity->save();

    return $entity;
  }

  /** * {@inheritdoc} */
  protected static function getExpectedCollectionCacheability(AccountInterface $account, array $collection, array $sparse_fieldset = NULL, $filtered = FALSE) {
    $cacheability = parent::getExpectedCollectionCacheability($account$collection$sparse_fieldset$filtered);
    if (static::entityAccess(reset($collection), 'view', $account)->isAllowed()) {
      $cacheability->addCacheContexts(['languages:language_interface']);
    }
    return $cacheability;
  }

}


      if (!isset($options['query'][static::QUERY_PARAMETER])) {
        $options['query'][static::QUERY_PARAMETER] = $langcode;
      }

      if ($bubbleable_metadata) {
        // Cached URLs that have been processed by this outbound path         // processor must be:         $bubbleable_metadata
          // - varied by the content language query parameter.           ->addCacheContexts(['url.query_args:' . static::QUERY_PARAMETER]);
      }
    }

    return $path;
  }

  /** * {@inheritdoc} */
  public function getLanguageSwitchLinks(Request $request$type, Url $url) {
    $links = [];
    
    $response = $this->request('GET', $collection_filter_url$request_options);
    $doc = Json::decode((string) $response->getBody());
    $this->assertCount(1, $doc['data']);
  }

  /** * {@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->addCacheContexts(['user']);
    }
    return $cacheability;
  }

}
new EntityCondition('uid', $current_user->id()),
        ]);
        $cacheability->addCacheTags($entity_type->getListCacheTags());
        break;

      case 'shortcut':
        // Unless the user can administer shortcuts, allow access only to the         // user's currently displayed shortcut set.         // @see \Drupal\shortcut\ShortcutAccessControlHandler::checkAccess()         if (!$current_user->hasPermission('administer shortcuts')) {
          $specific_condition = new EntityCondition('shortcut_set', shortcut_current_displayed_set()->id());
          $cacheability->addCacheContexts(['user']);
          $cacheability->addCacheTags($entity_type->getListCacheTags());
        }
        break;

      case 'user':
        // Disallow querying values of the anonymous user.         // @see \Drupal\user\UserAccessControlHandler::checkAccess()         $specific_condition = new EntityCondition('uid', '0', '!=');
        break;
    }

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