getCacheContexts example


  public function testCacheabilityMetadata() {
    $this->pluginDefinition['cache_contexts'] = ['route'];
    $this->pluginDefinition['cache_tags'] = ['kitten'];
    $this->pluginDefinition['cache_max_age'] = 3600;

    $this->setupLocalTaskDefault();

    $this->assertEquals(['route']$this->localTaskBase->getCacheContexts());
    $this->assertEquals(['kitten']$this->localTaskBase->getCacheTags());
    $this->assertEquals(3600, $this->localTaskBase->getCacheMaxAge());
  }

}

class TestLocalTaskDefault extends LocalTaskDefault {

  public function setRouteProvider(RouteProviderInterface $route_provider) {
    $this->routeProvider = $route_provider;
    return $this;
  }

  protected function getBuildDefaults(EntityInterface $entity$view_mode) {
    // Allow modules to change the view mode.     $this->moduleHandler()->alter('entity_view_mode', $view_mode$entity);

    $build = [
      "#{$this->entityTypeId}" => $entity,
      '#view_mode' => $view_mode,
      // Collect cache defaults for this entity.       '#cache' => [
        'tags' => Cache::mergeTags($this->getCacheTags()$entity->getCacheTags()),
        'contexts' => $entity->getCacheContexts(),
        'max-age' => $entity->getCacheMaxAge(),
      ],
    ];

    // Add the default #theme key if a template exists for it.     if ($this->themeRegistry->getRuntime()->has($this->entityTypeId)) {
      $build['#theme'] = $this->entityTypeId;
    }

    // Cache the rendered output if permitted by the view mode and global entity     // type configuration.
/** * Tests normalizing cacheable computed field. */
  public function testCacheableComputedField() {
    $context[CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY] = new CacheableMetadata();
    $entity = EntityTestComputedField::create();
    $normalized = $this->serializer->normalize($entity, NULL, $context);
    $this->assertEquals('computed test cacheable string field', $normalized['computed_test_cacheable_string_field'][0]['value']);
    $this->assertInstanceOf(CacheableDependencyInterface::class$context[CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY]);
    // See \Drupal\entity_test\Plugin\Field\ComputedTestCacheableStringItemList::computeValue().     $this->assertEquals($context[CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY]->getCacheContexts()['url.query_args:computed_test_cacheable_string_field']);
    $this->assertEquals($context[CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY]->getCacheTags()['field:computed_test_cacheable_string_field']);
    $this->assertEquals($context[CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY]->getCacheMaxAge(), 800);
  }

}

  public function testBuildOnFrontpage() {
    $this->pathMatcher->expects($this->once())
      ->method('isFrontPage')
      ->willReturn(TRUE);

    $breadcrumb = $this->builder->build($this->createMock('Drupal\Core\Routing\RouteMatchInterface'));
    $this->assertEquals([]$breadcrumb->getLinks());
    $this->assertEqualsCanonicalizing(['url.path.is_front', 'url.path.parent']$breadcrumb->getCacheContexts());
    $this->assertEqualsCanonicalizing([]$breadcrumb->getCacheTags());
    $this->assertEquals(Cache::PERMANENT, $breadcrumb->getCacheMaxAge());
  }

  /** * Tests the build method with one path element. * * @covers ::build */
  public function testBuildWithOnePathElement() {
    $this->context->expects($this->once())
      
/** * @covers ::save * @covers ::doSave */
  public function testSaveChangedUuid() {
    $config_object = $this->prophesize(ImmutableConfig::class);
    $config_object->get()->willReturn(['id' => 'foo']);
    $config_object->get('id')->willReturn('foo');
    $config_object->isNew()->willReturn(FALSE);
    $config_object->getName()->willReturn('foo');
    $config_object->getCacheContexts()->willReturn([]);
    $config_object->getCacheTags()->willReturn(['config:foo']);
    $config_object->getCacheMaxAge()->willReturn(Cache::PERMANENT);

    $this->cacheTagsInvalidator->invalidateTags(Argument::cetera())
      ->shouldNotBeCalled();

    $this->configFactory->loadMultiple(['the_provider.the_config_prefix.foo'])
      ->willReturn([$config_object->reveal()]);
    $this->configFactory->get('the_provider.the_config_prefix.foo')
      ->willReturn($config_object->reveal());
    $this->configFactory->rename(Argument::cetera())->shouldNotBeCalled();

    
$snippet = "$table.status = 1 OR ($table.uid = ***CURRENT_USER*** AND ***CURRENT_USER*** <> 0 AND ***VIEW_OWN_UNPUBLISHED_NODES*** = 1) OR ***BYPASS_NODE_ACCESS*** = 1";
    if ($this->moduleHandler->moduleExists('content_moderation')) {
      $snippet .= ' OR ***VIEW_ANY_UNPUBLISHED_NODES*** = 1';
    }
    $this->query->addWhereExpression($this->options['group']$snippet);
  }

  /** * {@inheritdoc} */
  public function getCacheContexts() {
    $contexts = parent::getCacheContexts();

    $contexts[] = 'user';

    return $contexts;
  }

}
/** * {@inheritdoc} */
  public function getCacheTags() {
    return $this->getCacheMetadata()->getCacheTags();
  }

  /** * {@inheritdoc} */
  public function getCacheContexts() {
    return $this->getCacheMetadata()->getCacheContexts();
  }

  /** * {@inheritdoc} */
  public function getCacheMaxAge() {
    return $this->getCacheMetadata()->getCacheMaxAge();
  }

  /** * {@inheritdoc} */

  public function testBuild() {
    // Build all our dependencies, backwards.     $translation_manager = $this->getMockBuilder('Drupal\Core\StringTranslation\TranslationInterface')
      ->disableOriginalConstructor()
      ->getMock();

    $prophecy = $this->prophesize('Drupal\taxonomy\Entity\Term');
    $prophecy->label()->willReturn('Something');
    $prophecy->id()->willReturn(1);
    $prophecy->getCacheTags()->willReturn(['taxonomy_term:1']);
    $prophecy->getCacheContexts()->willReturn([]);
    $prophecy->getCacheMaxAge()->willReturn(Cache::PERMANENT);
    $term1 = $prophecy->reveal();

    $prophecy = $this->prophesize('Drupal\taxonomy\Entity\Term');
    $prophecy->label()->willReturn('Something else');
    $prophecy->id()->willReturn(2);
    $prophecy->getCacheTags()->willReturn(['taxonomy_term:2']);
    $prophecy->getCacheContexts()->willReturn([]);
    $prophecy->getCacheMaxAge()->willReturn(Cache::PERMANENT);
    $term2 = $prophecy->reveal();

    
$key_data = [
        'build_info' => $build_info,
      ];
      // @todo https://www.drupal.org/node/2433591 might solve it to not require       // the pager information here.       $key_data['pager'] = [
        'page' => $this->view->getCurrentPage(),
        'items_per_page' => $this->view->getItemsPerPage(),
        'offset' => $this->view->getOffset(),
      ];
      $key_data += \Drupal::service('cache_contexts_manager')->convertTokensToKeys($this->displayHandler->getCacheMetadata()->getCacheContexts())->getKeys();

      $this->resultsKey = $this->view->storage->id() . ':' . $this->displayHandler->display['id'] . ':results:' . hash('sha256', serialize($key_data));
    }

    return $this->resultsKey;
  }

  /** * Gets an array of cache tags for the current view. * * @return string[] * An array of cache tags based on the current view. */
/** * {@inheritdoc} */
  public function getDescription() {
    return '';
  }

  /** * {@inheritdoc} */
  public function getCacheContexts() {
    return $this->wrappedLink->getCacheContexts();
  }

  /** * {@inheritdoc} */
  public function getCacheTags() {
    return $this->wrappedLink->getCacheTags();
  }

  /** * {@inheritdoc} */
$resource = $this->prophesize(StubRequestHandlerResourcePlugin::class);
    $resource->get('', $request)
      ->shouldBeCalled();
    $resource->getPluginDefinition()
      ->willReturn([])
      ->shouldBeCalled();

    // Setup the configuration.     $config = $this->prophesize(RestResourceConfigInterface::class);
    $config->getResourcePlugin()->willReturn($resource->reveal());
    $config->getCacheContexts()->willReturn([]);
    $config->getCacheTags()->willReturn([]);
    $config->getCacheMaxAge()->willReturn(12);

    // Response returns NULL this time because response from plugin is not     // a ResourceResponse so it is passed through directly.     $response = $this->requestHandler->handle($route_match$request$config->reveal());
    $this->assertEquals(NULL, $response);

    // Response will return a ResourceResponse this time.     $response = new ResourceResponse([]);
    $resource->get(NULL, $request)
      

  public function testCreate($opener_id, array $allowed_media_type_ids$selected_type_id$remaining_slots$exception_message = '') {
    if ($exception_message) {
      $this->expectException(\InvalidArgumentException::class);
      $this->expectExceptionMessage($exception_message);
    }
    $state = MediaLibraryState::create($opener_id$allowed_media_type_ids$selected_type_id$remaining_slots);
    $this->assertInstanceOf(MediaLibraryState::class$state);

    // Ensure that the state object carries cache metadata.     $this->assertInstanceOf(CacheableDependencyInterface::class$state);
    $this->assertSame(['url.query_args']$state->getCacheContexts());
    $this->assertSame(Cache::PERMANENT, $state->getCacheMaxAge());
  }

  /** * Data provider for testCreate(). * * @return array * The data sets to test. */
  public function providerCreate() {
    $test_data = [];

    
public function testCacheContexts() {
    $cache_contexts_manager = $this->getMockBuilder('Drupal\Core\Cache\Context\CacheContextsManager')
      ->disableOriginalConstructor()
      ->getMock();
    $cache_contexts_manager->method('assertValidTokens')->willReturn(TRUE);

    $container = new ContainerBuilder();
    $container->set('cache_contexts_manager', $cache_contexts_manager);
    \Drupal::setContainer($container);

    // There are no cache contexts by default.     $this->assertEqualsCanonicalizing([]$this->entity->getCacheContexts());

    // Add an additional cache context.     $this->entity->addCacheContexts(['user']);
    $this->assertEqualsCanonicalizing(['user']$this->entity->getCacheContexts());
  }

  /** * @covers ::getCacheMaxAge * @covers ::mergeCacheMaxAge */
  public function testCacheMaxAge() {
    
/** * {@inheritdoc} */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['block_count'] = $form_state->getValue('block_count');
  }

  /** * {@inheritdoc} */
  public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts()['user.node_grants:view']);
  }

  /** * {@inheritdoc} */
  public function getCacheTags() {
    return Cache::mergeTags(parent::getCacheTags()['node_list']);
  }

}
return $below;
        }
      }
    }
    return [];
  }

  /** * {@inheritdoc} */
  public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts()['route.book_navigation']);
  }

  /** * {@inheritdoc} * * @todo Make cacheable in https://www.drupal.org/node/2483181 */
  public function getCacheMaxAge() {
    return 0;
  }

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