applyTo example

'tags' => [
          'build-tag',
          'test',
        ],
        'max-age' => -1,
      ],
    ];

    $subscriber->onBuildRender($event);
    $result = $event->getBuild();
    $this->assertEquals($expected_build$result);
    $event->getCacheableMetadata()->applyTo($result);
    $this->assertEqualsCanonicalizing($expected_build_with_expected_cache['#cache']$result['#cache']);
  }

  /** * @covers ::onBuildRender * * @dataProvider providerBlockTypes */
  public function testOnBuildRenderWithoutPreviewFallbackString($refinable_dependent_access) {
    $contexts = [];
    if ($refinable_dependent_access) {
      

  private static function getUrlWithReplacedCsrfTokenPlaceholder(Url $url): string {
    $generated_url = $url->toString(TRUE);
    $url_with_csrf_token_placeholder = [
      '#plain_text' => $generated_url->getGeneratedUrl(),
    ];
    $generated_url->applyTo($url_with_csrf_token_placeholder);
    return (string) \Drupal::service('renderer')->renderPlain($url_with_csrf_token_placeholder);
  }

}

  protected function bubble(GeneratedUrl $generated_url, array $options = []) {
    // Bubbling metadata makes sense only if the code is executed inside a     // render context. All code running outside controllers has no render     // context by default, so URLs used there are not supposed to affect the     // response cacheability.     if ($this->renderer->hasRenderContext()) {
      $build = [];
      $generated_url->applyTo($build);
      $this->renderer->render($build);
    }
  }

  /** * {@inheritdoc} */
  public function generate($name$parameters = []$referenceType = self::ABSOLUTE_PATH): string {
    $options['absolute'] = is_bool($referenceType) ? $referenceType : $referenceType === self::ABSOLUTE_URL;
    $generated_url = $this->generateFromRoute($name$parameters$options, TRUE);
    $this->bubble($generated_url);
    
$output = '';
      }
      // Many routes have dots as route name, while some special ones like       // <front> have <> characters in them.       $url = $link->getUrlObject();
      $id = str_replace(['.', '<', '>']['-', '', '']$url->isRouted() ? $url->getRouteName() : $url->getUri());

      $subtrees[$id] = $output;
    }

    // Store the subtrees, along with the cacheability metadata.     $cacheability->applyTo($data);
    $data['#subtrees'] = $subtrees;

    return $data;
  }

  /** * {@inheritdoc} */
  public static function trustedCallbacks() {
    return ['preRenderAdministrationTray', 'preRenderGetRenderedSubtrees'];
  }

}
    // RendererInterface::render() outside of a render context, then the     // bubbleable metadata for that is stored in the current render context.     if (!$context->isEmpty()) {
      /** @var \Drupal\Core\Render\BubbleableMetadata $early_rendering_bubbleable_metadata */
      $early_rendering_bubbleable_metadata = $context->pop();

      // If a render array or AjaxResponse is returned by the controller, merge       // the "lost" bubbleable metadata.       if (is_array($response)) {
        BubbleableMetadata::createFromRenderArray($response)
          ->merge($early_rendering_bubbleable_metadata)
          ->applyTo($response);
      }
      elseif ($response instanceof AjaxResponse) {
        $response->addAttachments($early_rendering_bubbleable_metadata->getAttachments());
        // @todo Make AjaxResponse cacheable in         // https://www.drupal.org/node/956186. Meanwhile, allow contrib         // subclasses to be.         if ($response instanceof CacheableResponseInterface) {
          $response->addCacheableDependency($early_rendering_bubbleable_metadata);
        }
      }
      // If a non-Ajax Response or domain object is returned and it cares about
$build = [$view];
      }
    }
    // @todo Remove in https://www.drupal.org/project/drupal/issues/2367555.     catch (EnforcedResponseException $e) {
      throw $e;
    }
    catch (\Exception $e) {
      $build = [];
      $this->logger->warning('The field "%field" failed to render with the error of "%error".', ['%field' => $this->fieldName, '%error' => $e->getMessage()]);
    }
    CacheableMetadata::createFromRenderArray($build)->addCacheableDependency($this)->applyTo($build);
    return $build;
  }

  /** * {@inheritdoc} */
  public function getPreviewFallbackString() {
    return new TranslatableMarkup('"@field" field', ['@field' => $this->getFieldDefinition()->getLabel()]);
  }

  /** * {@inheritdoc} */
'#cache' => [
        'max-age' => $max_age,
      ],
    ];
    $this->assertEquals($expected$object->toRenderable());

    // Test retrieving the formatted time difference string.     $this->assertEquals($string$object->getString());

    // Test applying cacheability data to an existing build.     $build = [];
    CacheableMetadata::createFromObject($object)->applyTo($build);
    $this->assertEquals($max_age$build['#cache']['max-age']);
  }

  /** * Tests that an RFC2822 formatted date always returns an English string. * * @see http://www.faqs.org/rfcs/rfc2822.html * * @covers ::format */
  public function testRfc2822DateFormat(): void {
    
foreach ($images as $delta => $image) {
      $image_uri = $image->getFileUri();
      $url = $image_style ? $file_url_generator->transformRelative($image_style->buildUrl($image_uri)) : $file_url_generator->generateString($image_uri);

      // Add cacheability metadata from the image and image style.       $cacheability = CacheableMetadata::createFromObject($image);
      if ($image_style) {
        $cacheability->addCacheableDependency(CacheableMetadata::createFromObject($image_style));
      }

      $elements[$delta] = ['#markup' => $url];
      $cacheability->applyTo($elements[$delta]);
    }
    return $elements;
  }

}
new BubbleableMetadata()[]new BubbleableMetadata()],
      [new BubbleableMetadata()['library' => ['core/foo']](new BubbleableMetadata())->setAttachments(['library' => ['core/foo']])],
      [(new BubbleableMetadata())->setAttachments(['library' => ['core/foo']])['library' => ['core/bar']](new BubbleableMetadata())->setAttachments(['library' => ['core/foo', 'core/bar']])],
    ];
  }

  /** * @covers ::applyTo * @dataProvider providerTestApplyTo */
  public function testApplyTo(BubbleableMetadata $metadata, array $render_array, array $expected) {
    $this->assertNull($metadata->applyTo($render_array));
    $this->assertEquals($expected$render_array);
  }

  /** * Provides test data for testApplyTo(). * * @return array */
  public function providerTestApplyTo() {
    $data = [];

    
$tree_link_cacheability = new CacheableMetadata();
    $items = $this->buildItems($tree$tree_access_cacheability$tree_link_cacheability);

    $build = [];

    // Apply the tree-wide gathered access cacheability metadata and link     // cacheability metadata to the render array. This ensures that the     // rendered menu is varied by the cache contexts that the access results     // and (dynamic) links depended upon, and invalidated by the cache tags     // that may change the values of the access results and links.     $tree_cacheability = $tree_access_cacheability->merge($tree_link_cacheability);
    $tree_cacheability->applyTo($build);

    if ($items) {
      // Make sure Drupal\Core\Render\Element::children() does not re-order the       // links.       $build['#sorted'] = TRUE;
      // Get the menu name from the last link.       $item = end($items);
      $link = $item['original_link'];
      $menu_name = $link->getMenuName();
      // Add the theme wrapper for outer markup.       // Allow menu-specific theme overrides.

      if (!isset($options[$menu_parent])) {
        // The requested menu parent cannot be found in the menu anymore. Try         // setting it to the top level in the current menu.         [$menu_name] = explode(':', $menu_parent, 2);
        $menu_parent = $menu_name . ':';
      }
      if (isset($options[$menu_parent])) {
        // Only provide the default value if it is valid among the options.         $element += ['#default_value' => $menu_parent];
      }
      $options_cacheability->applyTo($element);
      return $element;
    }
    return [];
  }

  /** * Returns the maximum depth of the possible parents of the menu link. * * @param string $id * The menu link plugin ID or an empty value for a new link. * * @return int * The depth related to the depth of the given menu link. */
$this->t('Operations'),
      ];
    }

    $build['#title'] = $this->t('Translations of %label', ['%label' => $entity->label() ?? $entity->id()]);

    // Add metadata to the build render array to let other modules know about     // which entity this is.     $build['#entity'] = $entity;
    $cacheability
      ->addCacheTags($entity->getCacheTags())
      ->applyTo($build);

    $build['content_translation_overview'] = [
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $rows,
    ];

    return $build;
  }

  /** * Builds an add translation page. * * @param \Drupal\Core\Language\LanguageInterface $source * The language of the values being translated. Defaults to the entity * language. * @param \Drupal\Core\Language\LanguageInterface $target * The language of the translated values. Defaults to the current content * language. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The route match object from which to extract the entity type. * @param string $entity_type_id * (optional) The entity type ID. * * @return array * A processed form array ready to be rendered. */
$page['#sorted'] = TRUE;
    $cacheable_metadata->addCacheContexts(['user.node_grants:view']);

    // Display the reading history if that module is enabled.     if ($this->moduleHandler()->moduleExists('history')) {
      // Reading history is tracked for authenticated users only.       if ($this->currentUser()->isAuthenticated()) {
        $page['#attached']['library'][] = 'tracker/history';
      }
      $cacheable_metadata->addCacheContexts(['user.roles:authenticated']);
    }
    $cacheable_metadata->applyTo($page);
    return $page;
  }

}


        // 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) + [
      'max_width' => [
        
$format_id = $element['#format'];
    $filter_types_to_skip = $element['#filter_types_to_skip'];
    $text = $element['#text'];
    $langcode = $element['#langcode'];

    if (!isset($format_id)) {
      $filter_settings = static::configFactory()->get('filter.settings');
      $format_id = $filter_settings->get('fallback_format');
      // Ensure 'filter.settings' cacheability is respected.       CacheableMetadata::createFromRenderArray($element)
        ->addCacheableDependency($filter_settings)
        ->applyTo($element);
    }
    /** @var \Drupal\filter\Entity\FilterFormat $format **/
    $format = FilterFormat::load($format_id);
    // If the requested text format doesn't exist or its disabled, the text     // cannot be filtered.     if (!$format || !$format->status()) {
      $message = !$format ? 'Missing text format: %format.' : 'Disabled text format: %format.';
      static::logger('filter')->alert($message['%format' => $format_id]);
      $element['#markup'] = '';
      return $element;
    }

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