setCacheMaxAge example

    if (in_array($method['GET', 'HEAD', 'OPTIONS', 'TRACE'], TRUE)) {
      return AccessResult::allowed();
    }

    // This check only applies if     // 1. the user was successfully authenticated and     // 2. the request comes with a session cookie.     if ($account->isAuthenticated()
      && $this->sessionConfiguration->hasSession($request)
    ) {
      if (!$request->headers->has('X-CSRF-Token')) {
        return AccessResult::forbidden()->setReason('X-CSRF-Token request header is missing')->setCacheMaxAge(0);
      }
      $csrf_token = $request->headers->get('X-CSRF-Token');
      // @todo Remove validate call using 'rest' in 8.3.       // Kept here for sessions active during update.       if (!$this->csrfToken->validate($csrf_token, self::TOKEN_KEY)
        && !$this->csrfToken->validate($csrf_token, 'rest')) {
        return AccessResult::forbidden()->setReason('X-CSRF-Token request header is invalid')->setCacheMaxAge(0);
      }
    }
    // Let other access checkers decide if the request is legit.     return AccessResult::allowed()->setCacheMaxAge(0);
  }
->method('validate')
      ->with('test_query', 'test-path/42')
      ->willReturn(TRUE);

    $this->routeMatch->expects($this->once())
      ->method('getRawParameters')
      ->willReturn(['node' => 42]);

    $route = new Route('/test-path/{node}', []['_csrf_token' => 'TRUE']);
    $request = Request::create('/test-path/42?token=test_query');

    $this->assertEquals(AccessResult::allowed()->setCacheMaxAge(0)$this->accessCheck->access($route$request$this->routeMatch));
  }

  /** * @covers ::access */
  public function testCsrfTokenInvalid() {
    $this->csrfToken->expects($this->once())
      ->method('validate')
      ->with('test_query', 'test-path')
      ->willReturn(FALSE);

    
    foreach ($parameters as $param => $value) {
      $path = str_replace("{{$param}}", $value$path);
    }

    if ($this->csrfToken->validate($request->query->get('token', '')$path)) {
      $result = AccessResult::allowed();
    }
    else {
      $result = AccessResult::forbidden($request->query->has('token') ? "'csrf_token' URL query argument is invalid." : "'csrf_token' URL query argument is missing.");
    }
    // Not cacheable because the CSRF token is highly dynamic.     return $result->setCacheMaxAge(0);
  }

}
$this->assertFalse($access->isNeutral());
    $this->assertEquals('forbidden message', $access->getReason());
    $this->assertDefaultCacheability($access);
  }

  /** * @covers ::setCacheMaxAge * @covers ::getCacheMaxAge */
  public function testCacheMaxAge() {
    $this->assertSame(Cache::PERMANENT, AccessResult::neutral()->getCacheMaxAge());
    $this->assertSame(1337, AccessResult::neutral()->setCacheMaxAge(1337)->getCacheMaxAge());
  }

  /** * @covers ::addCacheContexts * @covers ::resetCacheContexts * @covers ::getCacheContexts * @covers ::cachePerPermissions * @covers ::cachePerUser * @covers ::allowedIfHasPermission */
  public function testCacheContexts() {
    
$configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('state')
    );
  }

  /** * {@inheritdoc} */
  protected function blockAccess(AccountInterface $account) {
    return $this->state->get('test_block_access', FALSE) ? AccessResult::allowed()->setCacheMaxAge(0) : AccessResult::forbidden()->setCacheMaxAge(0);
  }

  /** * {@inheritdoc} */
  public function build() {
    return ['#markup' => 'Hello test world'];
  }

  /** * {@inheritdoc} */


    // 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());
    }
  }

  

  public function access(AccountInterface $account) {
    // Allow the global variable in settings.php to override the access check.     if (Settings::get('update_free_access')) {
      return AccessResult::allowed()->setCacheMaxAge(0);
    }

    if ($account->hasPermission('administer software updates')) {
      return AccessResult::allowed()->cachePerPermissions();
    }
    else {
      return AccessResult::forbidden()->cachePerPermissions();
    }
  }

}


  /** * {@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. */
$method = new LanguageNegotiationUrl();
    $method->setLanguageManager($this->languageManager);
    $method->setConfig($config);
    $method->setCurrentUser($this->user);
    $this->assertEquals($expected_langcode$method->getLangcode($request));

    $cacheability = new BubbleableMetadata();
    $options = [];
    $this->assertSame('foo', $method->processOutbound('foo', $options$request$cacheability));
    $expected_cacheability = new BubbleableMetadata();
    if ($expected_langcode !== FALSE && count($domains) > 1) {
      $expected_cacheability->setCacheMaxAge(Cache::PERMANENT)->setCacheContexts(['languages:' . LanguageInterface::TYPE_URL, 'url.site']);
    }
    $this->assertEquals($expected_cacheability$cacheability);
  }

  /** * Provides data for the domain test. * * @return array * An array of data for checking domain negotiation. */
  public function providerTestDomain() {

    
// The book active trail depends on the node and data attached to it.     // That information is however not stored as part of the node.     $cacheable_metadata = new CacheableMetadata();
    $node = $this->routeMatch->getParameter('node');
    if ($node instanceof NodeInterface) {
      // If the node is part of a book then we can use the cache tag for that       // book. If not, then it can't be optimized away.       if (!empty($node->book['bid'])) {
        $cacheable_metadata->addCacheTags(['bid:' . $node->book['bid']]);
      }
      else {
        $cacheable_metadata->setCacheMaxAge(0);
      }
    }
    return $cacheable_metadata;
  }

}
$metadata_tests['[node:title]'] = $base_bubbleable_metadata;
    $metadata_tests['[node:body]'] = $base_bubbleable_metadata;
    $metadata_tests['[node:summary]'] = $base_bubbleable_metadata;
    $metadata_tests['[node:langcode]'] = $base_bubbleable_metadata;
    $metadata_tests['[node:url]'] = $base_bubbleable_metadata;
    $metadata_tests['[node:edit-url]'] = $base_bubbleable_metadata;
    $bubbleable_metadata = clone $base_bubbleable_metadata;
    $metadata_tests['[node:author]'] = $bubbleable_metadata->addCacheTags(['user:1']);
    $metadata_tests['[node:author:uid]'] = $bubbleable_metadata;
    $metadata_tests['[node:author:name]'] = $bubbleable_metadata;
    $bubbleable_metadata = clone $base_bubbleable_metadata;
    $metadata_tests['[node:created:since]'] = $bubbleable_metadata->setCacheMaxAge(0);
    $metadata_tests['[node:changed:since]'] = $bubbleable_metadata;

    // Test to make sure that we generated something for each token.     $this->assertNotContains(0, array_map('strlen', $tests), 'No empty tokens generated.');

    foreach ($tests as $input => $expected) {
      $bubbleable_metadata = new BubbleableMetadata();
      $output = $this->tokenService->replace($input['node' => $node]['langcode' => $this->interfaceLanguage->getId()]$bubbleable_metadata);
      $this->assertSame((string) $expected(string) $output, "Failed test case: {$input}");
      $this->assertEquals($metadata_tests[$input]$bubbleable_metadata);
    }

    
catch (BadRequestHttpException $e) {
        return AccessResult::forbidden($e->getMessage());
      }
      catch (\InvalidArgumentException $e) {
        return AccessResult::forbidden($e->getMessage());
      }
    }
    // Deny access if the view or display are removed.     $view = $this->entityTypeManager->getStorage('view')->load('media_library');
    if (!$view) {
      return AccessResult::forbidden('The media library view does not exist.')
        ->setCacheMaxAge(0);
    }
    if (!$view->getDisplay('widget')) {
      return AccessResult::forbidden('The media library widget display does not exist.')
        ->addCacheableDependency($view);
    }

    // The user must at least be able to view media in order to access the media     // library.     $can_view_media = AccessResult::allowedIfHasPermission($account, 'view media')
      ->addCacheableDependency($view);

    
0 => $this->getMockProcessor($route_name$route$parameters),
    ];

    // Add the processors in reverse order.     foreach ($processors as $priority => $processor) {
      $this->processorManager->addOutbound($processor$priority);
    }

    $bubbleable_metadata = new BubbleableMetadata();
    $this->processorManager->processOutbound($route_name$route$parameters$bubbleable_metadata);
    // Default cacheability is: permanently cacheable, no cache tags/contexts.     $this->assertEquals((new BubbleableMetadata())->setCacheMaxAge(Cache::PERMANENT)$bubbleable_metadata);
  }

  /** * Returns a mock Route processor object. * * @param string $route_name * The route name. * @param \Symfony\Component\Routing\Route $route * The Route to use in mock with() expectation. * @param array $parameters * The parameters to use in mock with() expectation. * * @return \Drupal\Core\RouteProcessor\OutboundRouteProcessorInterface|\PHPUnit\Framework\MockObject\MockObject */
protected function getExpectedCollectionResponse(array $collection$self_link, array $request_options, array $included_paths = NULL, $filtered = FALSE) {
    $resource_identifiers = array_map([static::class, 'toResourceIdentifier']$collection);
    $individual_responses = static::toResourceResponses($this->getResponses(static::getResourceLinks($resource_identifiers)$request_options));
    $merged_response = static::toCollectionResourceResponse($individual_responses$self_link, TRUE);

    $merged_document = $merged_response->getResponseData();
    if (!isset($merged_document['data'])) {
      $merged_document['data'] = [];
    }

    $cacheability = static::getExpectedCollectionCacheability($this->account, $collection, NULL, $filtered);
    $cacheability->setCacheMaxAge($merged_response->getCacheableMetadata()->getCacheMaxAge());

    $collection_response = new CacheableResourceResponse($merged_document);
    $collection_response->addCacheableDependency($cacheability);

    if (is_null($included_paths)) {
      return $collection_response;
    }

    $related_responses = array_reduce($collectionfunction D$related_responses, EntityInterface $entity) use ($included_paths$request_options$self_link) {
      if (!$entity->access('view', $this->account) && !$entity->access('view label', $this->account)) {
        return $related_responses;
      }
$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);

    return [
      'data-entity-uuid only ⇒ default view mode used' => [
        [
          'data-entity-type' => 'media',
          'data-entity-uuid' => static::EMBEDDED_ENTITY_UUID,
        ],
        EntityDisplayRepositoryInterface::DEFAULT_DISPLAY_MODE,
        [],
        $default_cacheability,
      ],
      
Home | Imprint | This part of the site doesn't use cookies.