transformRelative example

$node = Node::load($nid);

    // Get node field original image URI.     $fid = $node->get($field_name)->target_id;
    $original_uri = File::load($fid)->getFileUri();

    // Test that image is displayed using newly created style.     /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');

    $this->drupalGet('node/' . $nid);
    $this->assertSession()->responseContains($file_url_generator->transformRelative($style->buildUrl($original_uri)));

    // Rename the style and make sure the image field is updated.     $new_style_name = strtolower($this->randomMachineName(10));
    $new_style_label = $this->randomString();
    $edit = [
      'name' => $new_style_name,
      'label' => $new_style_label,
    ];
    $this->drupalGet($style_path . $style_name);
    $this->submitForm($edit, 'Save');
    $this->assertSession()->statusMessageContains('Changes to the style have been saved.', 'status');
    
/** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this->container->get('renderer');

    // Create an image.     $files = $this->drupalGetTestFiles('image');
    $file = reset($files);
    $original_uri = \Drupal::service('file_system')->copy($file->uri, 'public://', FileSystemInterface::EXISTS_RENAME);

    // Create a style.     $style = ImageStyle::create(['name' => 'test', 'label' => 'Test']);
    $style->save();
    $url = \Drupal::service('file_url_generator')->transformRelative($style->buildUrl($original_uri));

    // Create a test entity with the image field set.     $entity = EntityTest::create();
    $entity->image_test->target_id = $this->image->id();
    $entity->image_test->alt = NULL;
    $entity->image_test->uri = $original_uri;
    $image = $this->imageFactory->get('public://example.jpg');
    $entity->save();

    // Create the base element that we'll use in the tests below.     $path = $this->randomMachineName();
    

    $this->assertEquals(SAVED_UPDATED, $image_style->save());

    // Create a copy of a test image file in root.     $test_uri = 'public://image-test-do.png';
    \Drupal::service('file_system')->copy('core/tests/fixtures/files/image-test.png', $test_uri, FileSystemInterface::EXISTS_REPLACE);
    $this->assertFileExists($test_uri);

    // Execute the image style on the test image via a GET request.     $derivative_uri = 'public://styles/image_effect_test/public/image-test-do.png.jpeg';
    $this->assertFileDoesNotExist($derivative_uri);
    $url = \Drupal::service('file_url_generator')->transformRelative($image_style->buildUrl($test_uri));
    $this->drupalGet($this->getAbsoluteUrl($url));
    $this->assertSession()->statusCodeEquals(200);
    $this->assertFileExists($derivative_uri);
  }

}
// Disable file_test.module's hook_file_url_alter() implementation.     \Drupal::state()->set('file_test.hook_file_url_alter', NULL);

    // Create a mock Request for transformRelative().     $request = Request::create($GLOBALS['base_url']);
    $this->container->get('request_stack')->push($request);
    \Drupal::setContainer($this->container);

    // Shipped file.     $filepath = 'core/assets/vendor/jquery/jquery.min.js';
    $url = $this->fileUrlGenerator->generateAbsoluteString($filepath);
    $this->assertSame(base_path() . $filepath$this->fileUrlGenerator->transformRelative($url));

    // Managed file.     $uri = $this->createUri();
    $url = $this->fileUrlGenerator->generateAbsoluteString($uri);
    $public_directory_path = \Drupal::service('stream_wrapper_manager')
      ->getViaScheme('public')
      ->getDirectoryPath();
    $this->assertSame(base_path() . $public_directory_path . '/' . rawurlencode(\Drupal::service('file_system')
      ->basename($uri))$this->fileUrlGenerator->transformRelative($url));
  }

  
    $this->moduleHandler->alter('file_url', $uri);

    $scheme = StreamWrapperManager::getScheme($uri);

    if (!$scheme) {
      $baseUrl = $relative ? base_path() : $this->requestStack->getCurrentRequest()->getSchemeAndHttpHost() . base_path();
      return $this->generatePath($baseUrl$uri);
    }
    elseif ($scheme == 'http' || $scheme == 'https' || $scheme == 'data') {
      // Check for HTTP and data URI-encoded URLs so that we don't have to       // implement getExternalUrl() for the HTTP and data schemes.       return $relative ? $this->transformRelative($uri) : $uri;
    }
    elseif ($wrapper = $this->streamWrapperManager->getViaUri($uri)) {
      // Attempt to return an external URL using the appropriate wrapper.       $externalUrl = $wrapper->getExternalUrl();
      return $relative ? $this->transformRelative($externalUrl) : $externalUrl;
    }
    throw new InvalidStreamWrapperException();
  }

  /** * Generate a URL path. * * @param string $base_url * The base URL. * @param string $uri * The URI. * * @return string * The URL path. */
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
    $file_system = \Drupal::service('file_system');
    $original_uri = $file_system->copy($file->uri, 'public://', FileSystemInterface::EXISTS_RENAME);

    // Create a style.     /** @var \Drupal\image\ImageStyleInterface $style */
    $style = ImageStyle::create(['name' => 'test', 'label' => 'Test']);
    $style->save();
    $generated_uri = 'public://styles/test/public/' . $file_system->basename($original_uri);
    /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    $url = $file_url_generator->transformRelative($style->buildUrl($original_uri));

    $variables = [
      '#theme' => 'image_style',
      '#style_name' => 'test',
      '#uri' => $original_uri,
      '#width' => 40,
      '#height' => 20,
    ];
    // Verify that the original image matches the hard-coded values.     $image_file = $image_factory->get($original_uri);
    $this->assertEquals($variables['#width']$image_file->getWidth());
    
// Test the image URL formatter without an image style.     $display_options = [
      'type' => 'image_url',
      'settings' => ['image_style' => ''],
    ];
    $expected_url = $file->createFileUrl();
    $this->assertEquals($expected_url$node->{$field_name}->view($display_options)[0]['#markup']);

    // Test the image URL formatter with an image style.     $display_options['settings']['image_style'] = 'thumbnail';
    $expected_url = \Drupal::service('file_url_generator')->transformRelative(ImageStyle::load('thumbnail')->buildUrl($image_uri));
    $this->assertEquals($expected_url$node->{$field_name}->view($display_options)[0]['#markup']);

    // Test the settings summary.     $display_options = [
      'type' => 'image_url',
      'settings' => [
        'image_style' => 'thumbnail',
      ],
    ];
    $display = \Drupal::service('entity_display.repository')->getViewDisplay('node', $node->getType(), 'default');
    $display->setComponent($field_name$display_options)->save();
    
// Early opt-out if the field is empty.       return $elements;
    }

    /** @var \Drupal\image\ImageStyleInterface $image_style */
    $image_style = $this->imageStyleStorage->load($this->getSetting('image_style'));
    /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    /** @var \Drupal\file\FileInterface[] $images */
    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;
  }
// Save a new picture.     $image = current($this->drupalGetTestFiles('image'));
    $file = $this->saveUserPicture($image);

    $node = $this->drupalCreateNode(['type' => 'article']);

    // Enable user pictures on nodes.     $this->config('system.theme.global')->set('features.node_user_picture', TRUE)->save();

    $image_style_id = $this->config('core.entity_view_display.user.user.compact')->get('content.user_picture.settings.image_style');
    $style = ImageStyle::load($image_style_id);
    $image_url = \Drupal::service('file_url_generator')->transformRelative($style->buildUrl($file->getFileUri()));
    $alt_text = 'Profile picture for user ' . $this->webUser->getAccountName();

    // Verify that the image is displayed on the node page.     $this->drupalGet('node/' . $node->id());
    $elements = $this->cssSelect('article > footer img[alt="' . $alt_text . '"][src="' . $image_url . '"]');
    $this->assertCount(1, $elements, 'User picture with alt text found on node page.');

    // Enable user pictures on comments, instead of nodes.     $this->config('system.theme.global')
      ->set('features.node_user_picture', FALSE)
      ->set('features.comment_user_picture', TRUE)
      
    $large_style = ImageStyle::load('large');
    $large_style->createDerivative($image_uri$large_style->buildUri($image_uri));

    // Output should contain all image styles and all breakpoints.     $this->drupalGet('node/' . $nid);
    if (!$empty_styles) {
      $this->assertSession()->responseContains('/styles/medium/');
      // Assert the empty image is present.       $this->assertSession()->responseContains('data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==');
      $thumbnail_style = ImageStyle::load('thumbnail');
      // Assert the output of the 'srcset' attribute (small multipliers first).       $this->assertSession()->responseContains('data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== 1x, ' . $this->fileUrlGenerator->transformRelative($thumbnail_style->buildUrl($image_uri)) . ' 1.5x');
      $this->assertSession()->responseContains('/styles/medium/');
      // Assert the output of the original image.       $this->assertSession()->responseContains($this->fileUrlGenerator->generateString($image_uri) . ' 3x');
      // Assert the output of the breakpoints.       $this->assertSession()->responseContains('media="(min-width: 0px)"');
      $this->assertSession()->responseContains('media="(min-width: 560px)"');
      // Assert the output of the 'sizes' attribute.       $this->assertSession()->responseContains('sizes="(min-width: 700px) 700px, 100vw"');
      $this->assertSession()->responseMatches('/media="\(min-width: 560px\)".+?sizes="\(min-width: 700px\) 700px, 100vw"/');
      // Assert the output of the 'srcset' attribute (small images first).       $medium_style = ImageStyle::load('medium');
      
'multiplier' => '2x',
        ],
      ],
      '#width' => rand(0, 1000) . 'px',
      '#height' => rand(0, 500) . 'px',
      '#alt' => $this->randomMachineName(),
      '#title' => $this->randomMachineName(),
    ];
    $this->render($image);

    // Make sure the srcset attribute has the correct value.     $this->assertRaw($this->fileUrlGenerator->transformRelative($this->fileUrlGenerator->generateString($this->testImages[0])) . ' 1x, ' . $this->fileUrlGenerator->transformRelative($this->fileUrlGenerator->generateString($this->testImages[1])) . ' 2x', 'Correct output for image with srcset attribute and multipliers.');
  }

  /** * Tests that an image with the srcset and widths is output correctly. */
  public function testThemeImageWithSrcsetWidth() {
    // Test with multipliers.     $widths = [
      rand(0, 500) . 'w',
      rand(500, 1000) . 'w',
    ];
    
$_SERVER['REQUEST_URI'] = '/';
    $_SERVER['REQUEST_METHOD'] = 'GET';
    $_SERVER['SCRIPT_NAME'] = '/index.php';
    $_SERVER['SCRIPT_FILENAME'] = '/index.php';
    $_SERVER['PHP_SELF'] = '/index.php';
    $_SERVER['HTTP_USER_AGENT'] = 'Drupal command line';
    $_SERVER['HTTPS'] = $https;

    $request = Request::createFromGlobals();
    \Drupal::requestStack()->push($request);

    $this->assertSame($expected, \Drupal::service('file_url_generator')->transformRelative($url));
  }

  public function providerFileUrlTransformRelative() {
    $data = [
      'http' => [
        'example.com',
        80,
        '',
        'http://example.com/page',
        '/page',
      ],
      
Home | Imprint | This part of the site doesn't use cookies.