getCacheTags example

'#access' => $this->configuration['use_site_slogan'],
    ];

    return $build;
  }

  /** * {@inheritdoc} */
  public function getCacheTags() {
    return Cache::mergeTags(
      parent::getCacheTags(),
      $this->configFactory->get('system.site')->getCacheTags()
    );
  }

}

        ];

        // An empty title attribute will disable title inheritance, so only         // add it if the resource has a title.         $title = $resource->getTitle();
        if ($title) {
          $element[$delta]['#attributes']['title'] = $title;
        }

        CacheableMetadata::createFromObject($resource)
          ->addCacheTags($this->config->getCacheTags())
          ->applyTo($element[$delta]);
      }
    }
    return $element;
  }

  /** * {@inheritdoc} */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form = parent::settingsForm($form$form_state) + [
      

  protected function assertDrupalResponseCacheability($expect_cache, CacheableDependencyInterface $expected_metadata, Response $response) {
    $this->assertTrue(in_array($expect_cache['HIT', 'MISS', FALSE], TRUE), 'Cache is HIT, MISS, FALSE.');
    $this->assertSame($expected_metadata->getCacheContexts()explode(' ', $response->getHeaderLine('X-Drupal-Cache-Contexts')));
    $this->assertSame($expected_metadata->getCacheTags()explode(' ', $response->getHeaderLine('X-Drupal-Cache-Tags')));
    $max_age_message = $expected_metadata->getCacheMaxAge();
    if ($max_age_message === 0) {
      $max_age_message = '0 (Uncacheable)';
    }
    elseif ($max_age_message === -1) {
      $max_age_message = '-1 (Permanent)';
    }
    $this->assertSame($max_age_message$response->getHeaderLine('X-Drupal-Cache-Max-Age'));
    if ($expect_cache) {
      $this->assertSame($expect_cache$response->getHeaderLine('X-Drupal-Cache'));
    }
  }

  protected function assertAccess(AccessResultInterface $expected_access_result, array $expected_cache_contexts, array $expected_cache_tags, AccessResultInterface $actual): void {
    $this->assertSame($expected_access_result->isAllowed()$actual->isAllowed());
    $this->assertSame($expected_access_result->isForbidden()$actual->isForbidden());
    $this->assertSame($expected_access_result->isNeutral()$actual->isNeutral());

    $actual_cache_contexts = $actual->getCacheContexts();
    sort($expected_cache_contexts);
    sort($actual_cache_contexts);
    $this->assertSame($expected_cache_contexts$actual_cache_contexts);

    $actual_cache_tags = $actual->getCacheTags();
    sort($expected_cache_tags);
    sort($actual_cache_tags);
    $this->assertSame($expected_cache_tags$actual_cache_tags);
  }

  /** * Data provider for testAccess(). * * @return array * The data sets to test. */
  
public function testImageFormatterCacheTags() {
    // Create a test entity with the image field set.     $entity = EntityTest::create([
      'name' => $this->randomMachineName(),
    ]);
    $entity->{$this->fieldName}->generateSampleItems(2);
    $entity->save();

    // Generate the render array to verify if the cache tags are as expected.     $build = $this->display->build($entity);

    $this->assertEquals($entity->{$this->fieldName}[0]->entity->getCacheTags()$build[$this->fieldName][0]['#cache']['tags'], 'First image cache tags is as expected');
    $this->assertEquals($entity->{$this->fieldName}[1]->entity->getCacheTags()$build[$this->fieldName][1]['#cache']['tags'], 'Second image cache tags is as expected');
  }

  /** * Tests ImageFormatter's handling of SVG images. * * @requires extension gd */
  public function testImageFormatterSvg() {
    // Install the default image styles.     $this->installConfig(['image']);

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

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

}

  public function viewElements(FieldItemListInterface $items$langcode) {
    $elements = [];

    foreach ($this->getEntitiesToView($items$langcode) as $delta => $entity) {
      $elements[$delta] = [
        '#theme' => 'username',
        '#account' => $entity,
        '#link_options' => ['attributes' => ['rel' => 'author']],
        '#cache' => [
          'tags' => $entity->getCacheTags(),
        ],
      ];
    }

    return $elements;
  }

  /** * {@inheritdoc} */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    
$entity->formatted_text = [
      'value' => 'Hello, world!',
      'format' => 'my_text_format',
    ];
    $entity->save();

    foreach ($formatters as $formatter) {
      // Verify the text field formatter's render array.       $build = $entity->get('formatted_text')->view(['type' => $formatter]);
      \Drupal::service('renderer')->renderRoot($build[0]);
      $this->assertSame("<p>Hello, world!</p>\n", (string) $build[0]['#markup']);
      $this->assertEquals(FilterFormat::load('my_text_format')->getCacheTags()$build[0]['#cache']['tags']new FormattableMarkup('The @formatter formatter has the expected cache tags when formatting a formatted text field.', ['@formatter' => $formatter]));
    }
  }

}

  protected function getExpectedCacheTags() {
    $expected_cache_tags = [
      'config:rest.resource.entity.' . static::$entityTypeId,
    ];
    if (!static::$auth) {
      $expected_cache_tags[] = 'config:user.role.anonymous';
    }
    $expected_cache_tags[] = 'http_response';
    return Cache::mergeTags($expected_cache_tags$this->entity->getCacheTags());
  }

  /** * The expected cache contexts for the GET/HEAD response of the test entity. * * @see ::testGet * * @return string[] */
  protected function getExpectedCacheContexts() {
    return [
      

      '#in_preview' => FALSE,
    ];

    $block = $this->prophesize(BlockPluginInterface::class)->willImplement(PreviewFallbackInterface::class);
    $this->blockManager->createInstance('block_plugin_id', ['id' => 'block_plugin_id'])->willReturn($block->reveal());

    $access_result = AccessResult::allowed();
    $block->access($this->account->reveal(), TRUE)->willReturn($access_result);
    $block->build()->willReturn($block_content);
    $block->getCacheContexts()->willReturn([]);
    $block->getCacheTags()->willReturn([]);
    $block->getCacheMaxAge()->willReturn(Cache::PERMANENT);
    $block->getPluginId()->willReturn('block_plugin_id');
    $block->getBaseId()->willReturn('block_plugin_id');
    $block->getDerivativeId()->willReturn(NULL);
    $block->getConfiguration()->willReturn([]);
    $block->getPreviewFallbackString()->willReturn($placeholder_label);

    $section = [
      new SectionComponent('some_uuid', 'content', ['id' => 'block_plugin_id']),
    ];
    $expected = [
      
->method('getCacheTags')
      ->willReturn(['node:1']);
    $cacheable_dependency->expects($this->once())
      ->method('getCacheContexts')
      ->willReturn(['route']);
    $cacheable_dependency->expects($this->once())
      ->method('getCacheMaxAge')
      ->willReturn(60);

    $context = Context::createFromContext($context$cacheable_dependency);
    $this->assertSame($cacheable_dependency$context->getContextData());
    $this->assertEquals(['node:1']$context->getCacheTags());
    $this->assertEquals(['route']$context->getCacheContexts());
    $this->assertEquals(60, $context->getCacheMaxAge());
  }

  /** * Set up mocks for the getDefaultValue() method call. * * @param mixed $default_value * The default value to assign to the mock context definition. */
  protected function setUpDefaultValue($default_value = NULL) {
    
$header = [$this->t('Attachment')$this->t('Size')];
      $rows = [];
      foreach ($files as $file) {
        $item = $file->_referringItem;
        $rows[] = [
          [
            'data' => [
              '#theme' => 'file_link',
              '#file' => $file,
              '#description' => $this->getSetting('use_description_as_link_text') ? $item->description : NULL,
              '#cache' => [
                'tags' => $file->getCacheTags(),
              ],
            ],
          ],
          ['data' => $file->getSize() !== NULL ? format_size($file->getSize()) : $this->t('Unknown')],
        ];
      }

      $elements[0] = [];
      if (!empty($rows)) {
        $elements[0] = [
          '#theme' => 'table__file_formatter_table',
          

  public function getCacheTags() {
    $this->initDisplay();
    /** @var \Drupal\views\Plugin\views\cache\CachePluginBase $cache */
    $cache = $this->display_handler->getPlugin('cache');
    return $cache->getCacheTags();
  }

  /** * Builds the render array outline for the given display. * * This render array has a #pre_render callback which will call * ::executeDisplay in order to actually execute the view and then build the * final render array structure. * * @param string $display_id * The display ID. * @param array $args * An array of arguments passed along to the view. * @param bool $cache * (optional) Should the result be render cached. * * @return array|null * A renderable array with #type 'view' or NULL if the display ID was * invalid. */

  public static function createFromObject($object) {
    if ($object instanceof CacheableDependencyInterface) {
      $meta = new static();
      $meta->cacheContexts = $object->getCacheContexts();
      $meta->cacheTags = $object->getCacheTags();
      $meta->cacheMaxAge = $object->getCacheMaxAge();
      return $meta;
    }

    // Objects that don't implement CacheableDependencyInterface must be assumed     // to be uncacheable, so set max-age 0.     $meta = new static();
    $meta->cacheMaxAge = 0;
    return $meta;
  }

}

  }

  /** * {@inheritdoc} */
  public function getCacheTags() {
    // Even when the menu block renders to the empty string for a user, we want     // the cache tag for this menu to be set: whenever the menu is changed, this     // menu block must also be re-rendered for that user, because maybe a menu     // link that is accessible for that user has been added.     $cache_tags = parent::getCacheTags();
    $cache_tags[] = 'config:system.menu.' . $this->getDerivativeId();
    return $cache_tags;
  }

  /** * {@inheritdoc} */
  public function getCacheContexts() {
    // ::build() uses MenuLinkTreeInterface::getCurrentRouteMenuTreeParameters()     // to generate menu tree parameters, and those take the active menu trail     // into account. Therefore, we must vary the rendered menu by the active
Home | Imprint | This part of the site doesn't use cookies.