setCacheContexts example

$config_translation->delete();
      }
    }
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata($name) {
    $metadata = new CacheableMetadata();
    if ($this->language) {
      $metadata->setCacheContexts(['languages:language_interface']);
    }
    return $metadata;
  }

}

  }

  /** * {@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',
        $is_authenticated ? 'user:2' : 'user:0',
      ]);
/** * {@inheritdoc} */
  public function getRuntimeContexts(array $unqualified_context_ids) {
    $current_user = $this->userStorage->load($this->account->id());

    $context1 = EntityContext::fromEntity($current_user, 'User A');
    $context2 = EntityContext::fromEntity($current_user, 'User B');

    $cacheability = new CacheableMetadata();
    $cacheability->setCacheContexts(['user']);

    $context1->addCacheableDependency($cacheability);
    $context2->addCacheableDependency($cacheability);

    return [
      'userA' => $context1,
      'userB' => $context2,
    ];
  }

  /** * {@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} */
  protected static function getExpectedCollectionCacheability(AccountInterface $account, array $collection, array $sparse_fieldset = NULL, $filtered = FALSE) {
    return parent::getExpectedCollectionCacheability($account$collection$sparse_fieldset$filtered)
      ->addCacheTags(['user:2'])
      ->addCacheContexts(['user.roles']);
  }

}
return "$message.";
  }

  /** * {@inheritdoc} */
  protected function getExpectedUnauthorizedAccessCacheability() {
    return (new CacheableMetadata())
      ->setCacheTags(static::$auth
        ? ['4xx-response', 'http_response']
        : ['4xx-response', 'config:user.role.anonymous', 'http_response'])
      ->setCacheContexts(['user.permissions']);
  }

  /** * The cacheability of unauthorized 'view' entity access. * * @param bool $is_authenticated * Whether the current request is authenticated or not. This matters for * some entity access control handlers, but not for most. * * @return \Drupal\Core\Cache\CacheableMetadata * The expected cacheability. */
default:
        return parent::getExpectedUnauthorizedAccessMessage($method);
    }
  }

  /** * {@inheritdoc} */
  protected function getExpectedUnauthorizedAccessCacheability() {
    return (new CacheableMetadata())
      ->setCacheTags(['4xx-response', 'http_response'])
      ->setCacheContexts(['user.permissions']);
  }

  /** * Empty function. * * Needed by PHPStan for unused function * CookieResourceTestTrait::assertResponseWhenMissingAuthentication(). */
  protected function getExpectedUnauthorizedEntityAccessCacheability($is_authenticated) {}

}

      elseif (isset($route_contexts['node_preview']) && $node = $this->routeMatch->getParameter('node_preview')) {
        $value = $node;
      }
      elseif ($this->routeMatch->getRouteName() == 'node.add') {
        $node_type = $this->routeMatch->getParameter('node_type');
        $value = Node::create(['type' => $node_type->id()]);
      }
    }

    $cacheability = new CacheableMetadata();
    $cacheability->setCacheContexts(['route']);

    $context = new Context($context_definition$value);
    $context->addCacheableDependency($cacheability);
    $result['node'] = $context;

    return $result;
  }

  /** * {@inheritdoc} */
  
if (isset($route_parameters['taxonomy_term']) && $term = $this->routeMatch->getParameter('taxonomy_term')) {
        $value = $term;
      }
      elseif ($this->routeMatch->getRouteName() == 'entity.taxonomy_term.add_form') {
        $vocabulary = $this->routeMatch->getParameter('taxonomy_vocabulary');
        $value = Term::create(['vid' => $vocabulary->id()]);
      }
    }

    $cacheability = new CacheableMetadata();
    $cacheability->setCacheContexts(['route']);

    $context = new Context($context_definition$value);
    $context->addCacheableDependency($cacheability);
    $result['taxonomy_term'] = $context;

    return $result;
  }

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

  /** * {@inheritdoc} */
  public function getCacheableMetadata($name) {
    $metadata = new CacheableMetadata();
    if ($name === 'block.block.config_override_test') {
      $metadata
        ->setCacheContexts(['config_override_integration_test'])
        ->setCacheTags(['config_override_integration_test_tag']);
    }
    return $metadata;
  }

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

    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,
      ],
use Drupal\Tests\UnitTestCase;

/** * @group Http */
class CacheableExceptionTest extends UnitTestCase {

  /** * @covers \Drupal\Core\Http\Exception\CacheableHttpException */
  public function testCacheableHttpException() {
    $exception = new CacheableHttpException((new CacheableMetadata())->setCacheContexts(['route']), 500, 'test message', NULL, ['X-Drupal-Exception' => 'Test'], 123);
    $this->assertSame(['route']$exception->getCacheContexts());
    $this->assertSame(500, $exception->getStatusCode());
    $this->assertSame('test message', $exception->getMessage());
    $this->assertSame(['X-Drupal-Exception' => 'Test']$exception->getHeaders());
    $this->assertSame(123, $exception->getCode());
  }

  /** * @dataProvider providerTestExceptions */
  public function testExceptions($status_code$class$argument = NULL, $expected_headers = []) {
    
class ComputedTestCacheableStringItemList extends FieldItemList {

  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;
  }

}


  /** * @covers ::replace */
  public function testReplaceWithBubbleableMetadataObject() {
    $this->moduleHandler->expects($this->any())
      ->method('invokeAll')
      ->willReturn(['[node:title]' => 'hello world']);

    $bubbleable_metadata = new BubbleableMetadata();
    $bubbleable_metadata->setCacheContexts(['current_user']);
    $bubbleable_metadata->setCacheMaxAge(12);

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

    $result = $this->token->replace('[node:title]', ['node' => $node][]$bubbleable_metadata);
    $this->assertEquals('hello world', $result);

    
unset($language_types[$unqualified_context_id]);
        }
      }
    }

    $result = [];
    foreach ($language_types as $type_key) {
      if (isset($info[$type_key]['name'])) {
        $context = new Context(new ContextDefinition('language', $info[$type_key]['name'])$this->languageManager->getCurrentLanguage($type_key));

        $cacheability = new CacheableMetadata();
        $cacheability->setCacheContexts(['languages:' . $type_key]);
        $context->addCacheableDependency($cacheability);

        $result[$type_key] = $context;
      }
    }

    return $result;
  }

  /** * {@inheritdoc} */
$this->assertEquals('POST, PUT', $response->headers->get('Allow'));
    $this->assertEquals('application/json', $response->headers->get('Content-Type'));
  }

  public function providerTestOn4xx() {
    return [
      'uncacheable exception' => [
        new MethodNotAllowedHttpException(['POST', 'PUT'], 'test message'),
        JsonResponse::class,
      ],
      'cacheable exception' => [
        new CacheableMethodNotAllowedHttpException((new CacheableMetadata())->setCacheContexts(['route'])['POST', 'PUT'], 'test message'),
        CacheableJsonResponse::class,
      ],
    ];
  }

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