generateString example

    $this->drupalGet($this->assertLinkToCreatedMedia());

    // Assert the image element is present inside the media element and that its     // src attribute uses the large image style, the label is visually hidden,     // and there is no link to the image file.     $label = $assert_session->elementExists('xpath', '//div[contains(@class, "visually-hidden") and text()="Image"]');
    // The field is the parent div of the label.     $field = $label->getParent();
    $image_element = $field->find('css', 'img');
    /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    $expected_image_src = $file_url_generator->generateString(\Drupal::token()->replace('public://styles/large/public/[date:custom:Y]-[date:custom:m]/example_1.jpeg'));
    $this->assertStringContainsString($expected_image_src$image_element->getAttribute('src'));
    $assert_session->elementNotExists('css', 'a', $field);

    // Ensure the image has the correct alt attribute.     $this->assertSame('Image Alt Text 1', $image_element->getAttribute('alt'));

    // Load the media and check that all fields are properly populated.     $media = Media::load(1);
    $this->assertSame('example_1.jpeg', $media->getName());
    $this->assertSame('200', $media->get('field_string_width')->value);
    $this->assertSame('89', $media->get('field_string_height')->value);

    


    return $form;
  }

  /** * {@inheritdoc} */
  protected function viewValue(FieldItemInterface $item) {
    $value = $item->value;
    if ($this->getSetting('file_download_path')) {
      $value = $this->fileUrlGenerator->generateString($value);
    }
    return $value;
  }

  /** * {@inheritdoc} */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    return parent::isApplicable($field_definition) && $field_definition->getName() === 'uri';
  }

}
    $assert_session->elementTextContains('xpath', '//h1', $image_media_name);
    // Here we expect to see only the image, nothing else.     // Assert only one element in the content region.     $media_item = $assert_session->elementExists('xpath', '//div[@class="layout-content"]/div/div[2]');
    $assert_session->elementsCount('xpath', '/div', 1, $media_item);
    // Assert the image is present inside the media element.     $media_image = $assert_session->elementExists('xpath', '//img', $media_item);
    // Assert that the image src uses the large image style, the label is     // visually hidden, and there is no link to the image file.     /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    $expected_image_src = $file_url_generator->generateString(\Drupal::token()->replace('public://styles/large/public/[date:custom:Y]-[date:custom:m]/example_1.jpeg'));
    $this->assertStringContainsString($expected_image_src$media_image->getAttribute('src'));
    $field = $assert_session->elementExists('xpath', '/div[1]', $media_item);
    $assert_session->elementExists('xpath', '/div[@class="visually-hidden"]', $field);
    $assert_session->elementNotExists('xpath', '//a', $field);

    $test_filename = $this->randomMachineName() . '.txt';
    $test_filepath = 'public://' . $test_filename;
    file_put_contents($test_filepath$this->randomMachineName());
    $this->drupalGet("media/add/document");
    $page->attachFileToField("files[field_media_document_0]", \Drupal::service('file_system')->realpath($test_filepath));
    $result = $assert_session->waitForButton('Remove');
    
// This type attribute prevents this from being parsed as an             // inline script.             'type' => 'application/json',
            'data-drupal-selector' => 'drupal-settings-json',
          ];
          $element['#value'] = Json::encode($js_asset['data']);
          break;

        case 'file':
          $query_string = $js_asset['version'] == -1 ? $default_query_string : 'v=' . $js_asset['version'];
          $query_string_separator = str_contains($js_asset['data'], '?') ? '&' : '?';
          $element['#attributes']['src'] = $this->fileUrlGenerator->generateString($js_asset['data']);
          // Only add the cache-busting query string if this isn't an aggregate           // file.           if (!isset($js_asset['preprocessed'])) {
            $element['#attributes']['src'] .= $query_string_separator . ($js_asset['cache'] ? $query_string : REQUEST_TIME);
          }
          break;

        case 'external':
          $element['#attributes']['src'] = $js_asset['data'];
          break;

        
// Test Drupal\Core\StreamWrapper\LocalStream::getDirectoryPath().     $this->assertEquals(PublicStream::basePath()$stream_wrapper_manager->getViaScheme('public')->getDirectoryPath(), 'Expected default directory path was returned.');
    $file_system = \Drupal::service('file_system');
    assert($file_system instanceof FileSystemInterface);
    $this->assertEquals($file_system->getTempDirectory()$stream_wrapper_manager->getViaScheme('temporary')->getDirectoryPath(), 'Expected temporary directory path was returned.');

    // Test FileUrlGeneratorInterface::generateString()     // TemporaryStream::getExternalUrl() uses Url::fromRoute(), which needs     // route information to work.     $file_url_generator = $this->container->get('file_url_generator');
    assert($file_url_generator instanceof FileUrlGeneratorInterface);
    $this->assertStringContainsString('system/temporary?file=test.txt', $file_url_generator->generateString('temporary://test.txt'), 'Temporary external URL correctly built.');
    $this->assertStringContainsString(Settings::get('file_public_path') . '/test.txt', $file_url_generator->generateString('public://test.txt'), 'Public external URL correctly built.');
    $this->assertStringContainsString('system/files/test.txt', $file_url_generator->generateString('private://test.txt'), 'Private external URL correctly built.');
  }

  /** * Tests some file handle functions. */
  public function testFileFunctions() {
    $filename = 'public://' . $this->randomMachineName();
    file_put_contents($filenamestr_repeat('d', 1000));

    
'responsive_image_style' => 'style_one',
      ],
    ];
    $display = $display_repository->getViewDisplay('node', 'article');
    $display->setComponent($field_name$display_options)
      ->save();

    $this->drupalGet('node/' . $nid);
    // No image style cache tag should be found.     $this->assertSession()->responseHeaderNotContains('X-Drupal-Cache-Tags', 'image_style:');

    $this->assertSession()->responseMatches('/<a(.*?)href="' . preg_quote($this->fileUrlGenerator->generateString($image_uri), '/') . '"(.*?)>\s*<picture/');
    // Verify that the image can be downloaded.     $this->assertEquals(file_get_contents($test_image->uri)$this->drupalGet($this->fileUrlGenerator->generateAbsoluteString($image_uri)), 'File was downloaded successfully.');
    if ($scheme == 'private') {
      // Only verify HTTP headers when using private scheme and the headers are       // sent by Drupal.       $this->assertSession()->responseHeaderEquals('Content-Type', 'image/png');
      $this->assertSession()->responseHeaderContains('Cache-Control', 'private');

      // Log out and ensure the file cannot be accessed.       $this->drupalLogout();
      $this->drupalGet($this->fileUrlGenerator->generateAbsoluteString($image_uri));
      
$this->expectException(InvalidStreamWrapperException::class);
    $result = $this->fileUrlGenerator->generate("foo://bar");
  }

  /** * Tests missing stream handler. * * @covers ::generateString */
  public function testGenerateStringMissingStreamWrapper() {
    $this->expectException(InvalidStreamWrapperException::class);
    $result = $this->fileUrlGenerator->generateString("foo://bar");
  }

  /** * Tests missing stream handler. * * @covers ::generateAbsoluteString */
  public function testGenerateAbsoluteStringMissingStreamWrapper() {
    $this->expectException(InvalidStreamWrapperException::class);
    $result = $this->fileUrlGenerator->generateAbsoluteString("foo://bar");
  }

  
'filters' => [],
    ])->save();

    $defaults = [
      'type' => 'article',
      'promote' => 1,
    ];
    /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    $this->drupalCreateNode($defaults + [
      'body' => [
        'value' => '<p><a href="' . $file_url_generator->generateString('public://root-relative') . '">Root-relative URL</a></p>',
        'format' => 'full_html',
      ],
    ]);
    $protocol_relative_url = substr($file_url_generator->generateAbsoluteString('public://protocol-relative')strlen(\Drupal::request()->getScheme() . ':'));
    $this->drupalCreateNode($defaults + [
      'body' => [
        'value' => '<p><a href="' . $protocol_relative_url . '">Protocol-relative URL</a></p>',
        'format' => 'full_html',
      ],
    ]);
    $absolute_url = $file_url_generator->generateAbsoluteString('public://absolute');
    
drupal_static_reset('theme_get_setting');

    $values = [
      'default_logo' => FALSE,
      'logo_path' => 'public://logo_with_scheme.png',
    ];
    theme_settings_convert_to_config($values$config)->save();

    // Tests logo path with scheme.     /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    $expected = $file_url_generator->generateString('public://logo_with_scheme.png');
    $this->assertEquals($expectedtheme_get_setting('logo.url', 'stark'));

    $values = [
      'default_logo' => FALSE,
      'logo_path' => $theme->getPath() . '/logo_relative_path.gif',
    ];
    theme_settings_convert_to_config($values$config)->save();

    drupal_static_reset('theme_get_setting');

    // Tests relative path.
// 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;
  }
// Specify a filesystem path to be used for the logo.     $file = current($this->drupalGetTestFiles('image'));
    $file_relative = strtr($file->uri, ['public:/' => PublicStream::basePath()]);
    $default_theme_path = 'core/themes/starterkit_theme';

    /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    $supported_paths = [
      // Raw stream wrapper URI.       $file->uri => [
        'form' => StreamWrapperManager::getTarget($file->uri),
        'src' => $file_url_generator->generateString($file->uri),
      ],
      // Relative path within the public filesystem.       StreamWrapperManager::getTarget($file->uri) => [
        'form' => StreamWrapperManager::getTarget($file->uri),
        'src' => $file_url_generator->generateString($file->uri),
      ],
      // Relative path to a public file.       $file_relative => [
        'form' => $file_relative,
        'src' => $file_url_generator->generateString($file->uri),
      ],
      
$privateKeyPath = $input->getOption('private-key-path') ?? ($this->projectDir . '/config/jwt/private.pem');
        $publicKeyPath = $input->getOption('public-key-path') ?? ($this->projectDir . '/config/jwt/public.pem');

        if (!\is_string($passphrase)) {
            $io->error('Passphrase is invalid');

            return self::FAILURE;
        }

        if ($input->getOption('use-env')) {
            [$private$public] = $this->jwtCertificateGenerator->generateString($passphrase);

            if ($output instanceof ConsoleOutputInterface) {
                $errorIo = new SymfonyStyle($input$output->getErrorOutput());

                $errorIo->info('Add these two environment variables to your .env file');
            }

            $io->writeln('JWT_PUBLIC_KEY=' . base64_encode($public));
            $io->writeln('JWT_PRIVATE_KEY=' . base64_encode($private));
            $io->writeln('');

            
if ($already_loaded) {
      $query_args['exclude'] = UrlHelper::compressQueryParameter(implode(',', $this->dependencyResolver->getMinimalRepresentativeSubset($already_loaded)));
    }

    // Generate a URL for each group of assets, but do not process them inline,     // this is done using optimizeGroup() when the asset path is requested.     foreach ($css_assets as $order => $css_asset) {
      if (!empty($css_asset['preprocessed'])) {
        $query = ['delta' => "$order"] + $query_args;
        $filename = 'css_' . $this->generateHash($css_asset) . '.css';
        $uri = 'assets://css/' . $filename;
        $css_assets[$order]['data'] = $this->fileUrlGenerator->generateString($uri) . '?' . UrlHelper::buildQuery($query);
      }
      unset($css_assets[$order]['items']);
    }

    return $css_assets;
  }

  /** * {@inheritdoc} */
  public function getAll() {
    
$assert_session->waitForElementVisible('css', '.ck-widget.image');

    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-balloon-panel .ck-text-alternative-form'));
    $alt_override_input = $page->find('css', '.ck-balloon-panel .ck-text-alternative-form input[type=text]');
    $this->assertSame('', $alt_override_input->getValue());
    $alt_override_input->setValue('</em> Kittens & llamas are cute');
    $this->getBalloonButton('Save')->click();
    $page->pressButton('Save');

    $uploaded_image = File::load(1);
    $image_uuid = $uploaded_image->uuid();
    $image_url = $this->container->get('file_url_generator')->generateString($uploaded_image->getFileUri());
    $this->drupalGet('node/1');
    $this->assertNotEmpty($assert_session->waitForElement('xpath', sprintf('//img[@alt="</em> Kittens & llamas are cute" and @data-entity-uuid="%s" and @data-entity-type="file"]', $image_uuid)));

    // Drupal CKEditor 5 integrations overrides the CKEditor 5 HTML writer to     // escape ampersand characters (&) and the angle brackets (< and >). This is     // required because \Drupal\Component\Utility\Xss::filter fails to parse     // element attributes with unescaped entities in value.     // @see https://www.drupal.org/project/drupal/issues/3227831     $this->assertEquals(sprintf('<img data-entity-uuid="%s" data-entity-type="file" src="%s" alt="&lt;/em&gt; Kittens &amp; llamas are cute">', $image_uuid$image_url), Node::load(1)->get('body')->value);
  }

  
'rel' => 'stylesheet',
      ],
    ];

    foreach ($css_assets as $css_asset) {
      $element = $link_element_defaults;
      $element['#attributes']['media'] = $css_asset['media'];

      switch ($css_asset['type']) {
        // For file items, output a LINK tag for file CSS assets.         case 'file':
          $element['#attributes']['href'] = $this->fileUrlGenerator->generateString($css_asset['data']);
          // Only add the cache-busting query string if this isn't an aggregate           // file.           if (!isset($css_asset['preprocessed'])) {
            $query_string_separator = str_contains($css_asset['data'], '?') ? '&' : '?';
            $element['#attributes']['href'] .= $query_string_separator . $query_string;
          }
          break;

        case 'external':
          $element['#attributes']['href'] = $css_asset['data'];
          break;

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