buildUri example

/** * Tests moving a randomly generated image. */
  public function testNormal() {
    // Pick a file for testing.     $file = File::create((array) current($this->drupalGetTestFiles('image')));

    // Create derivative image.     $styles = ImageStyle::loadMultiple();
    $style = reset($styles);
    $original_uri = $file->getFileUri();
    $derivative_uri = $style->buildUri($original_uri);
    $style->createDerivative($original_uri$derivative_uri);

    // Check if derivative image exists.     $this->assertFileExists($derivative_uri);

    // Clone the object so we don't have to worry about the function changing     // our reference copy.     $desired_filepath = 'public://' . $this->randomMachineName();
    $result = $this->fileRepository->move(clone $file$desired_filepath, FileSystemInterface::EXISTS_ERROR);

    // Check if image has been moved.
$this->style->save();

    // Create a new language.     ConfigurableLanguage::createFromLangcode('fr')->save();
  }

  /** * Tests \Drupal\image\ImageStyleInterface::buildUri(). */
  public function testImageStylePath() {
    $scheme = 'public';
    $actual = $this->style->buildUri("$scheme://foo/bar.gif");
    $expected = "$scheme://styles/" . $this->style->id() . "/$scheme/foo/bar.gif";
    $this->assertEquals($expected$actual, 'Got the path for a file URI.');

    $actual = $this->style->buildUri('foo/bar.gif');
    $expected = "$scheme://styles/" . $this->style->id() . "/$scheme/foo/bar.gif";
    $this->assertEquals($expected$actual, 'Got the path for a relative file path.');
  }

  /** * Tests an image style URL using the "public://" scheme. */
  
public function testFlushUserInterface() {
    $admin_path = 'admin/config/media/image-styles';

    // Create a new style.     $style_name = strtolower($this->randomMachineName(10));
    $style = ImageStyle::create(['name' => $style_name, 'label' => $this->randomString()]);
    $style->save();

    // Create an image to make sure it gets flushed.     $files = $this->drupalGetTestFiles('image');
    $image_uri = $files[0]->uri;
    $derivative_uri = $style->buildUri($image_uri);
    $this->assertTrue($style->createDerivative($image_uri$derivative_uri));
    $this->assertEquals(1, $this->getImageCount($style));

    // Go to image styles list page and check if the flush operation link     // exists.     $this->drupalGet($admin_path);
    $flush_path = $admin_path . '/manage/' . $style_name . '/flush';
    $this->assertSession()->linkByHrefExists($flush_path);

    // Flush the image style derivatives using the user interface.     $this->drupalGet($flush_path);
    

    return "$scheme://styles/{$this->id()}/$source_scheme/{$this->addExtension($path)}";
  }

  /** * {@inheritdoc} */
  public function buildUrl($path$clean_urls = NULL) {
    /** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
    $stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');

    $uri = $stream_wrapper_manager->normalizeUri($this->buildUri($path));

    // The token query is added even if the     // 'image.settings:allow_insecure_derivatives' configuration is TRUE, so     // that the emitted links remain valid if it is changed back to the default     // FALSE. However, sites which need to prevent the token query from being     // emitted at all can additionally set the     // 'image.settings:suppress_itok_output' configuration to TRUE to achieve     // that (if both are set, the security token will neither be emitted in the     // image derivative URL nor checked for in     // \Drupal\image\ImageStyleInterface::deliver()).     $token_query = [];
    

    public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface
    {
        // Merge the base URI into the request URI if needed.         $options = $this->prepareDefaults($options);

        return $this->transfer(
            $request->withUri($this->buildUri($request->getUri()$options)$request->hasHeader('Host')),
            $options
        );
    }

    /** * Send an HTTP request. * * @param array $options Request options to apply to the given * request and to the transfer. See \GuzzleHttp\RequestOptions. * * @throws GuzzleException */
$valid = $valid && $token_is_valid;
    }

    if (!$valid) {
      // Return a 404 (Page Not Found) rather than a 403 (Access Denied) as the       // image token is for DDoS protection rather than access checking. 404s       // are more likely to be cached (e.g. at a proxy) which enhances       // protection from DDoS.       throw new NotFoundHttpException();
    }

    $derivative_uri = $image_style->buildUri($image_uri);
    $derivative_scheme = $this->streamWrapperManager->getScheme($derivative_uri);

    if ($token_is_valid) {
      $is_public = ($scheme !== 'private');
    }
    else {
      $core_schemes = ['public', 'private', 'temporary'];
      $additional_public_schemes = array_diff(Settings::get('file_additional_public_schemes', [])$core_schemes);
      $public_schemes = array_merge(['public']$additional_public_schemes);
      $is_public = in_array($derivative_scheme$public_schemes, TRUE);
    }

    
// Image style that changes the extension.     $image_effect_id = $this->randomMachineName();
    $logger = $this->getMockBuilder('\Psr\Log\LoggerInterface')->getMock();
    $image_effect = $this->getMockBuilder('\Drupal\image\ImageEffectBase')
      ->setConstructorArgs([[]$image_effect_id[]$logger])
      ->getMock();
    $image_effect->expects($this->any())
      ->method('getDerivativeExtension')
      ->willReturn('png');

    $image_style = $this->getImageStyleMock($image_effect_id$image_effect);
    $this->assertEquals($image_style->buildUri('public://test.jpeg'), 'public://styles/' . $image_style->id() . '/public/test.jpeg.png');

    // Image style that doesn't change the extension.     $image_effect_id = $this->randomMachineName();
    $image_effect = $this->getMockBuilder('\Drupal\image\ImageEffectBase')
      ->setConstructorArgs([[]$image_effect_id[]$logger])
      ->getMock();
    $image_effect->expects($this->any())
      ->method('getDerivativeExtension')
      ->will($this->returnArgument(0));

    $image_style = $this->getImageStyleMock($image_effect_id$image_effect);
    
      $this->drupalLogin($this->adminUser);
    }

    // Use the responsive image formatter with a responsive image style.     $display_options['settings']['responsive_image_style'] = 'style_one';
    $display_options['settings']['image_link'] = '';
    $display->setComponent($field_name$display_options)
      ->save();

    // Create a derivative so at least one MIME type will be known.     $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/');
      
/** * Tests derivative creation with several source on a local writable stream. * * @dataProvider providerTestCustomStreamWrappers * * @param string $source_scheme * The source stream wrapper scheme. * @param string $expected_scheme * The derivative expected stream wrapper scheme. */
  public function testCustomStreamWrappers($source_scheme$expected_scheme) {
    $derivative_uri = $this->imageStyle->buildUri("$source_scheme://some/path/image.png");
    $derivative_scheme = StreamWrapperManager::getScheme($derivative_uri);

    // Check that the derivative scheme is the expected scheme.     $this->assertSame($expected_scheme$derivative_scheme);

    // Check that the derivative URI is the expected one.     $expected_uri = "$expected_scheme://styles/{$this->imageStyle->id()}/$source_scheme/some/path/image.png";
    $this->assertSame($expected_uri$derivative_uri);
  }

  /** * Provide test cases for testCustomStreamWrappers(). * * Derivatives created from writable source stream wrappers will inherit the * scheme from source. Derivatives created from read-only stream wrappers will * fall-back to the default scheme. * * @return array[] * An array having each element an array with three items: * - The source stream wrapper scheme. * - The derivative expected stream wrapper scheme. * - The stream wrapper service class. */
public function createSampleImage($style$wrapper) {
    static $file;

    if (!isset($file)) {
      $files = $this->drupalGetTestFiles('image');
      $file = reset($files);
    }

    // Make sure we have an image in our wrapper testing file directory.     $source_uri = \Drupal::service('file_system')->copy($file->uri, $wrapper . '://');
    // Build the derivative image.     $derivative_uri = $style->buildUri($source_uri);
    $derivative = $style->createDerivative($source_uri$derivative_uri);

    return $derivative ? $derivative_uri : FALSE;
  }

  /** * Count the number of images currently created for a style in a wrapper. */
  public function getImageCount($style$wrapper) {
    $count = 0;
    if (is_dir($wrapper . '://styles/' . $style->id())) {
      
Home | Imprint | This part of the site doesn't use cookies.