BubbleableMetadata example

$metadata_tests['[term:tid]'] = $base_bubbleable_metadata;
    $metadata_tests['[term:name]'] = $base_bubbleable_metadata;
    $metadata_tests['[term:description]'] = $base_bubbleable_metadata;
    $metadata_tests['[term:url]'] = $base_bubbleable_metadata;
    $metadata_tests['[term:node-count]'] = $base_bubbleable_metadata;
    $metadata_tests['[term:parent:name]'] = $base_bubbleable_metadata;
    $bubbleable_metadata = clone $base_bubbleable_metadata;
    $metadata_tests['[term:vocabulary:name]'] = $bubbleable_metadata->addCacheTags($this->vocabulary->getCacheTags());
    $metadata_tests['[term:vocabulary]'] = $bubbleable_metadata->addCacheTags($this->vocabulary->getCacheTags());

    foreach ($tests as $input => $expected) {
      $bubbleable_metadata = new BubbleableMetadata();
      $output = $token_service->replace($input['term' => $term1]['langcode' => $language_interface->getId()]$bubbleable_metadata);
      $this->assertSame((string) $expected(string) $output, "Failed test case: {$input}");
      $this->assertEquals($metadata_tests[$input]$bubbleable_metadata);
    }

    // Generate and test sanitized tokens for term2.     $tests = [];
    $tests['[term:tid]'] = $term2->id();
    $tests['[term:name]'] = $term2->getName();
    $tests['[term:description]'] = $term2->description->processed;
    $tests['[term:url]'] = $term2->toUrl('canonical', ['absolute' => TRUE])->toString();
    

  protected function setUp(): void {
    parent::setUp();

    $this->urlGenerator = \Drupal::urlGenerator();
  }

  /** * Tests the output process. */
  public function testProcessOutbound() {
    $expected_cacheability = (new BubbleableMetadata())->setCacheMaxAge(Cache::PERMANENT);

    $request_stack = \Drupal::requestStack();
    /** @var \Symfony\Component\Routing\RequestContext $request_context */
    $request_context = \Drupal::service('router.request_context');

    // Test request with subdir on homepage.     $server = [
      'SCRIPT_NAME' => '/subdir/index.php',
      'SCRIPT_FILENAME' => $this->root . '/index.php',
      'SERVER_NAME' => 'http://www.example.com',
    ];
    

  public function testProcessOutbound($path, array $options$expected_path) {
    $this->aliasManager->expects($this->any())
      ->method('getAliasByPath')
      ->willReturnMap([
        ['internal-url', NULL, 'urlalias'],
        ['url', NULL, 'url'],
      ]);

    $bubbleable_metadata = new BubbleableMetadata();
    $this->assertEquals($expected_path$this->pathProcessor->processOutbound($path$options, NULL, $bubbleable_metadata));
    // Cacheability of paths replaced with path aliases is permanent.     // @todo https://www.drupal.org/node/2480077     $this->assertEquals((new BubbleableMetadata())->setCacheMaxAge(Cache::PERMANENT)$bubbleable_metadata);
  }

  /** * @return array */
  public function providerTestProcessOutbound() {
    return [
      [
// Generate and test tokens.     $tests = [];
    $tests['[site:name]'] = Html::escape($config->get('name'));
    $tests['[site:slogan]'] = $safe_slogan;
    $tests['[site:mail]'] = $config->get('mail');
    $tests['[site:url]'] = Url::fromRoute('<front>', []$url_options)->toString();
    $tests['[site:url-brief]'] = preg_replace(['!^https?://!', '!/$!'], '', Url::fromRoute('<front>', []$url_options)->toString());
    $tests['[site:base-url]'] = 'http://localhost';
    $tests['[site:login-url]'] = Url::fromRoute('user.page', []$url_options)->toString();

    $base_bubbleable_metadata = new BubbleableMetadata();

    $metadata_tests = [];
    $metadata_tests['[site:name]'] = BubbleableMetadata::createFromObject(\Drupal::config('system.site'));
    $metadata_tests['[site:slogan]'] = BubbleableMetadata::createFromObject(\Drupal::config('system.site'));
    $metadata_tests['[site:mail]'] = BubbleableMetadata::createFromObject(\Drupal::config('system.site'));
    $bubbleable_metadata = clone $base_bubbleable_metadata;
    $metadata_tests['[site:base-url]'] = $bubbleable_metadata->addCacheContexts(['url.site']);
    $metadata_tests['[site:url]'] = $bubbleable_metadata->addCacheContexts(['url.site']);
    $metadata_tests['[site:url-brief]'] = $bubbleable_metadata;
    $metadata_tests['[site:login-url]'] = $bubbleable_metadata;

    
// Test node specific tokens.     $metadata_tests['[comment:entity:nid]'] = $bubbleable_metadata;
    $metadata_tests['[comment:entity:title]'] = $bubbleable_metadata;
    $bubbleable_metadata = clone $base_bubbleable_metadata;
    $metadata_tests['[comment:author:uid]'] = $bubbleable_metadata->addCacheTags(['user:2']);
    $metadata_tests['[comment:author:name]'] = $bubbleable_metadata;

    // Test to make sure that we generated something for each token.     $this->assertNotContains(0, array_map('strlen', $tests), 'No empty tokens generated.');

    foreach ($tests as $input => $expected) {
      $bubbleable_metadata = new BubbleableMetadata();
      $output = $token_service->replace($input['comment' => $comment]['langcode' => $language_interface->getId()]$bubbleable_metadata);
      $this->assertSame((string) $expected(string) $output, "Failed test case: {$input}");
      $this->assertEquals($metadata_tests[$input]$bubbleable_metadata);
    }

    // Test anonymous comment author.     $author_name = 'This is a random & " > string';
    $comment->setOwnerId(0)->setAuthorName($author_name);
    $input = '[comment:author]';
    $output = $token_service->replace($input['comment' => $comment]['langcode' => $language_interface->getId()]);
    $this->assertSame((string) Html::escape($author_name)(string) $output);
    
$metadata_tests['[view:id]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:title]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:url]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:total-rows]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:base-table]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:base-field]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:items-per-page]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:current-page]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:page-count]'] = $base_bubbleable_metadata;

    foreach ($expected as $token => $expected_output) {
      $bubbleable_metadata = new BubbleableMetadata();
      $output = $token_handler->replace($token['view' => $view][]$bubbleable_metadata);
      $this->assertSame($expected_output$outputnew FormattableMarkup('Token %token replaced correctly.', ['%token' => $token]));
      $this->assertEquals($metadata_tests[$token]$bubbleable_metadata);
    }
  }

  /** * Tests core token replacements generated from a view. */
  public function testTokenReplacementWithMiniPager() {
    $token_handler = \Drupal::token();
    
$metadata_tests['[file:created:short]'] = $bubbleable_metadata;
    $metadata_tests['[file:changed]'] = $bubbleable_metadata;
    $metadata_tests['[file:changed:short]'] = $bubbleable_metadata;
    $bubbleable_metadata = clone $base_bubbleable_metadata;
    $metadata_tests['[file:owner]'] = $bubbleable_metadata->addCacheTags(['user:2']);
    $metadata_tests['[file:owner:uid]'] = $bubbleable_metadata;

    // Test to make sure that we generated something for each token.     $this->assertNotContains(0, array_map('strlen', $tests), 'No empty tokens generated.');

    foreach ($tests as $input => $expected) {
      $bubbleable_metadata = new BubbleableMetadata();
      $output = $token_service->replace($input['file' => $file]['langcode' => $language_interface->getId()]$bubbleable_metadata);
      $this->assertEquals($expected$outputnew FormattableMarkup('Sanitized file token %token replaced.', ['%token' => $input]));
      $this->assertEquals($metadata_tests[$input]$bubbleable_metadata);
    }

    // Generate and test unsanitized tokens.     $tests['[file:name]'] = $file->getFilename();
    $tests['[file:path]'] = $file->getFileUri();
    $tests['[file:mime]'] = $file->getMimeType();
    $tests['[file:size]'] = format_size($file->getSize());

    
    $this->token->getInfo();
  }

  /** * @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);

    

  protected function getUploadLocation(array $settings) {
    $destination = trim($settings['file_directory'], '/');

    // Replace tokens. As the tokens might contain HTML we convert it to plain     // text.     $destination = PlainTextOutput::renderFromHtml($this->token->replace($destination[][]new BubbleableMetadata()));
    return $settings['uri_scheme'] . '://' . $destination;
  }

  /** * Retrieves the upload validators for a field definition. * * This is copied from \Drupal\file\Plugin\Field\FieldType\FileItem as there * is no entity instance available here that a FileItem would exist for. * * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition * The field definition for which to get validators. * * @return array * An array suitable for passing to file_save_upload() or the file field * element's '#upload_validators' property. */
$processors = [
      10 => $this->getMockProcessor($route_name$route$parameters),
      5 => $this->getMockProcessor($route_name$route$parameters),
      0 => $this->getMockProcessor($route_name$route$parameters),
    ];

    // Add the processors in reverse order.     foreach ($processors as $priority => $processor) {
      $this->processorManager->addOutbound($processor$priority);
    }

    $bubbleable_metadata = new BubbleableMetadata();
    $this->processorManager->processOutbound($route_name$route$parameters$bubbleable_metadata);
    // Default cacheability is: permanently cacheable, no cache tags/contexts.     $this->assertEquals((new BubbleableMetadata())->setCacheMaxAge(Cache::PERMANENT)$bubbleable_metadata);
  }

  /** * Returns a mock Route processor object. * * @param string $route_name * The route name. * @param \Symfony\Component\Routing\Route $route * The Route to use in mock with() expectation. * @param array $parameters * The parameters to use in mock with() expectation. * * @return \Drupal\Core\RouteProcessor\OutboundRouteProcessorInterface|\PHPUnit\Framework\MockObject\MockObject */

  public function getRouteLink(string $text, string $route, array $parameters = [], array $options = []): array {
    assert($this->accessManager instanceof AccessManagerInterface, "The access manager hasn't been set up. Any configuration YAML file with a service directive dealing with the Twig configuration can cause this, most likely found in a recently installed or changed module.");

    $bubbles = new BubbleableMetadata();
    $bubbles->addCacheTags(['route_match']);

    try {
      $access_object = $this->accessManager->checkNamedRoute($route$parameters, NULL, TRUE);
      $bubbles->addCacheableDependency($access_object);

      if ($access_object->isAllowed()) {
        $options['absolute'] = TRUE;
        $url = Url::fromRoute($route$parameters$options);
        // Generate the URL to check for parameter problems and collect         // cache metadata.

  protected function setUp(): void {
    parent::setUp();

    $this->urlGenerator = \Drupal::urlGenerator();
  }

  /** * Tests the output process. */
  public function testProcessOutbound() {
    $expected_cacheability = (new BubbleableMetadata())
      ->addCacheContexts(['route'])
      ->setCacheMaxAge(Cache::PERMANENT);

    $request_stack = \Drupal::requestStack();
    /** @var \Symfony\Component\Routing\RequestContext $request_context */
    $request_context = \Drupal::service('router.request_context');

    // Test request with subdir on homepage.     $server = [
      'SCRIPT_NAME' => '/subdir/index.php',
      'SCRIPT_FILENAME' => $this->root . '/index.php',
      

  public function tokenReplace(NodeInterface $node) {
    $bubbleable_metadata = new BubbleableMetadata();
    $build['#markup'] = $this->token->replace('Tokens: [node:nid] [current-user:uid]', ['node' => $node][]$bubbleable_metadata);
    $bubbleable_metadata->applyTo($build);

    return $build;
  }

  /** * Provides a token replacement with a node as well as the current user. * * This controller is for testing the token service's fallback behavior of * applying collected metadata to the currently active render context when an * explicit bubbleable metadata object isn't passed in. * * @param \Drupal\node\NodeInterface $node * The node. * * @return array * The render array. */
$metadata_tests['[user:last-login:short]'] = $bubbleable_metadata;
    $metadata_tests['[user:created]'] = $bubbleable_metadata;
    $metadata_tests['[user:created:short]'] = $bubbleable_metadata;
    $metadata_tests['[current-user:name]'] = $base_bubbleable_metadata->merge(BubbleableMetadata::createFromObject($global_account)->addCacheContexts(['user']));
    $metadata_tests['[current-user:account-name]'] = $base_bubbleable_metadata->merge(BubbleableMetadata::createFromObject($global_account)->addCacheContexts(['user']));
    $metadata_tests['[current-user:display-name]'] = $base_bubbleable_metadata->merge(BubbleableMetadata::createFromObject($global_account)->addCacheContexts(['user']));

    // Test to make sure that we generated something for each token.     $this->assertNotContains(0, array_map('strlen', $tests), 'No empty tokens generated.');

    foreach ($tests as $input => $expected) {
      $bubbleable_metadata = new BubbleableMetadata();
      $output = $token_service->replace($input['user' => $account]['langcode' => $language_interface->getId()]$bubbleable_metadata);
      $this->assertSame((string) $expected(string) $output, "Failed test case: {$input}");
      $this->assertEquals($metadata_tests[$input]$bubbleable_metadata);
    }

    // Generate tokens for the anonymous user.     $anonymous_user = User::load(0);
    $tests = [];
    $tests['[user:uid]'] = 'not yet assigned';
    $tests['[user:display-name]'] = $anonymous_user->getDisplayName();

    
/** * Tests the processOutbound() method with no _csrf_token route requirement. */
  public function testProcessOutboundNoRequirement() {
    $this->csrfToken->expects($this->never())
      ->method('get');

    $route = new Route('/test-path');
    $parameters = [];

    $bubbleable_metadata = new BubbleableMetadata();
    $this->processor->processOutbound('test', $route$parameters$bubbleable_metadata);
    // No parameters should be added to the parameters array.     $this->assertEmpty($parameters);
    // Cacheability of routes without a _csrf_token route requirement is     // unaffected.     $this->assertEquals((new BubbleableMetadata())$bubbleable_metadata);
  }

  /** * Tests the processOutbound() method with a _csrf_token route requirement. */
  
Home | Imprint | This part of the site doesn't use cookies.