getCacheMaxAge example

/** * {@inheritdoc} */
  public function getCacheContexts() {
    return \Drupal::state()->get('block_test.cache_contexts', []);
  }

  /** * {@inheritdoc} */
  public function getCacheMaxAge() {
    return \Drupal::state()->get('block_test.cache_max_age', parent::getCacheMaxAge());
  }

}
return $resource->getAuthorUrl();

      case 'provider_name':
        $provider = $resource->getProvider();
        return $provider ? $provider->getName() : '';

      case 'provider_url':
        $provider = $resource->getProvider();
        return $provider ? $provider->getUrl() : NULL;

      case 'cache_age':
        return $resource->getCacheMaxAge();

      case 'thumbnail_width':
        return $resource->getThumbnailWidth();

      case 'thumbnail_height':
        return $resource->getThumbnailHeight();

      case 'url':
        $url = $resource->getUrl();
        return $url ? $url->toString() : NULL;

      

  protected function mergeCacheabilityFromConditions(AccessResult $access, array $conditions) {
    foreach ($conditions as $condition) {
      if ($condition instanceof CacheableDependencyInterface) {
        $access->addCacheTags($condition->getCacheTags());
        $access->addCacheContexts($condition->getCacheContexts());
        $access->setCacheMaxAge(Cache::mergeMaxAges($access->getCacheMaxAge()$condition->getCacheMaxAge()));
      }
    }
  }

}

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

    $this->entityQuery->condition('uuid', 'baz')->willReturn($this->entityQuery);
    
->getMock();

    $forum_manager = $this->getMockBuilder('Drupal\forum\ForumManagerInterface')
      ->disableOriginalConstructor()
      ->getMock();

    $prophecy = $this->prophesize('Drupal\taxonomy\VocabularyInterface');
    $prophecy->label()->willReturn('Fora_is_the_plural_of_forum');
    $prophecy->id()->willReturn(5);
    $prophecy->getCacheTags()->willReturn(['taxonomy_vocabulary:5']);
    $prophecy->getCacheContexts()->willReturn([]);
    $prophecy->getCacheMaxAge()->willReturn(Cache::PERMANENT);

    $vocab_storage = $this->createMock('Drupal\Core\Entity\EntityStorageInterface');
    $vocab_storage->expects($this->any())
      ->method('load')
      ->willReturnMap([
        ['forums', $prophecy->reveal()],
      ]);

    $entity_type_manager = $this->createMock(EntityTypeManagerInterface::class);
    $entity_type_manager->expects($this->any())
      ->method('getStorage')
      
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();

    $forum_manager = $this->getMockBuilder('Drupal\forum\ForumManagerInterface')
      
return $tags;
  }

  /** * Gets the max age for the current view. * * @return int */
  public function getCacheMaxAge() {
    $max_age = $this->getDefaultCacheMaxAge();
    $max_age = Cache::mergeMaxAges($max_age$this->view->getQuery()->getCacheMaxAge());
    return $max_age;
  }

  /** * Returns the default cache max age. */
  protected function getDefaultCacheMaxAge() {
    // The default cache backend is not caching anything.     return 0;
  }

  
$this->assertSame($this->term1->label()$normalized['included'][1]['attributes']['name']);
    $this->assertCount(12, $normalized['included'][1]['attributes']);
    $this->assertTrue(!isset($normalized['included'][1]['attributes']['created']));
    // Make sure that the cache tags for the includes and the requested entities     // are bubbling as expected.     $this->assertEqualsCanonicalizing(
      ['file:1', 'node:1', 'taxonomy_term:1', 'taxonomy_term:2', 'user:1'],
      $jsonapi_doc_object->getCacheTags()
    );
    $this->assertSame(
      Cache::PERMANENT,
      $jsonapi_doc_object->getCacheMaxAge()
    );
  }

  /** * @covers ::normalize */
  public function testNormalizeUuid() {
    $resource_type = $this->container->get('jsonapi.resource_type.repository')->get('node', 'article');
    $resource_object = ResourceObject::createFromEntity($resource_type$this->node);
    $include_param = 'uid,field_tags';
    $includes = $this->includeResolver->resolve($resource_object$include_param);
    

  protected function getTestBlock(ProphecyInterface $entity_prophecy, array $configuration = [], array $plugin_definition = []) {
    $entity_prophecy->getCacheContexts()->willReturn([]);
    $entity_prophecy->getCacheTags()->willReturn([]);
    $entity_prophecy->getCacheMaxAge()->willReturn(0);

    $plugin_definition += [
      'provider' => 'test',
      'default_formatter' => '',
      'category' => 'Test',
      'admin_label' => 'Test Block',
      'bundles' => ['entity_test'],
      'context_definitions' => [
        'entity' => EntityContextDefinition::fromEntityTypeId('entity_test')->setLabel('Test'),
        'view_mode' => new ContextDefinition('string'),
      ],
    ];
$redirect_data = [
          '#cache_redirect' => TRUE,
          '#cache' => [
            // The cache keys of the current element; this remains the same             // across requests.             'keys' => $elements['#cache']['keys'],
            // The union of the current element's and stored cache contexts.             'contexts' => $redirect_cacheability_updated->getCacheContexts(),
            // The union of the current element's and stored cache tags.             'tags' => $redirect_cacheability_updated->getCacheTags(),
            // The union of the current element's and stored cache max-ages.             'max-age' => $redirect_cacheability_updated->getCacheMaxAge(),
            // The same cache bin as the one for the actual render cache items.             'bin' => $bin,
          ],
        ];
        $cache->set($pre_bubbling_cid$redirect_data$this->maxAgeToExpire($redirect_cacheability_updated->getCacheMaxAge()), Cache::mergeTags($redirect_data['#cache']['tags']['rendered']));
      }

      // Current cache contexts incomplete: this request only uses a subset of       // the cache contexts stored in the redirecting cache item. Vary by these       // additional (conditional) cache contexts as well, otherwise the       // redirecting cache item would be pointing to a cache item that can never
/** * {@inheritdoc} */
  public function getCacheTags() {
    return $this->cacheabilityMetadata->getCacheTags();
  }

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

  /** * {@inheritdoc} */
  public static function createFromContext(ContextInterface $old_context$value) {
    $context = new static($old_context->getContextDefinition()$value);
    $context->addCacheableDependency($old_context);
    if (method_exists($old_context, 'getTypedDataManager')) {
      $context->setTypedDataManager($old_context->getTypedDataManager());
    }
    

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

}
// Create the render array for the block as a whole.       // @see template_preprocess_block().       $build[$entity_id] = [
        '#cache' => [
          'keys' => ['entity_view', 'block', $entity->id()],
          'contexts' => Cache::mergeContexts(
            $entity->getCacheContexts(),
            $plugin->getCacheContexts()
          ),
          'tags' => $cache_tags,
          'max-age' => $plugin->getCacheMaxAge(),
        ],
        '#weight' => $entity->getWeight(),
      ];

      // Allow altering of cacheability metadata or setting #create_placeholder.       $this->moduleHandler->alter(['block_build', "block_build_" . $plugin->getBaseId()]$build[$entity_id]$plugin);

      if ($plugin instanceof MainContentBlockPluginInterface || $plugin instanceof TitleBlockPluginInterface) {
        // Immediately build a #pre_render-able block, since this block cannot         // be built lazily.         $build[$entity_id] += static::buildPreRenderableBlock($entity$this->moduleHandler());
      }
$contexts['layout_builder.entity'] = $context->reveal();

      $block->setAccessDependency($layout_entity)->shouldBeCalled();
    }
    else {
      $block = $this->prophesize(BlockPluginInterface::class)->willImplement(PreviewFallbackInterface::class);
    }
    $access_result = AccessResult::allowed();
    $block->access($this->account->reveal(), TRUE)->willReturn($access_result)->shouldBeCalled();
    $block->getCacheContexts()->willReturn([]);
    $block->getCacheTags()->willReturn(['test']);
    $block->getCacheMaxAge()->willReturn(Cache::PERMANENT);
    $block->getConfiguration()->willReturn([]);
    $block->getPluginId()->willReturn('block_plugin_id');
    $block->getBaseId()->willReturn('block_plugin_id');
    $block->getDerivativeId()->willReturn(NULL);
    $placeholder_label = 'Placeholder Label';
    $block->getPreviewFallbackString()->willReturn($placeholder_label);

    $block_content = [
      '#markup' => 'The block content.',
      '#cache' => ['tags' => ['build-tag']],
    ];
    
/** * {@inheritdoc} */
  public function getCacheContexts() {
    return $this->getCacheMetadata()->getCacheContexts();
  }

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

  /** * {@inheritdoc} */
  public function listTopics() {
    // Map the top level help topic plugins to a list of topic links.     return array_map(function DHelpTopicPluginInterface $topic) {
      return $topic->toLink();
    }$this->getPlugins());
  }

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