generateAbsoluteString example

/** * Invokes system_retrieve_file() in several scenarios. */
  public function testFileRetrieving() {
    // Test 404 handling by trying to fetch a randomly named file.     /** @var \Drupal\Core\File\FileSystemInterface $file_system */
    $file_system = \Drupal::service('file_system');
    $file_system->mkdir($sourcedir = 'public://' . $this->randomMachineName());
    // cSpell:disable-next-line     $filename = 'Файл для тестирования ' . $this->randomMachineName();
    $url = \Drupal::service('file_url_generator')->generateAbsoluteString($sourcedir . '/' . $filename);
    $retrieved_file = system_retrieve_file($url);
    $this->assertFalse($retrieved_file, 'Non-existent file not fetched.');

    // Actually create that file, download it via HTTP and test the returned path.     file_put_contents($sourcedir . '/' . $filename, 'testing');
    $retrieved_file = system_retrieve_file($url);

    // URLs could not contains characters outside the ASCII set so $filename     // has to be encoded.     $encoded_filename = rawurlencode($filename);

    
$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");
  }

  /** * Tests the rewriting of shipped file URLs by hook_file_url_alter(). * * @covers ::generateAbsoluteString */
  public function testShippedFileURL() {
    // Test generating a URL to a shipped file (i.e. a file that is part of     // Drupal core, a module or a theme, for example a JavaScript file).
    
$this->fileUrlGenerator = $this->container->get('file_url_generator');
    // Clear out any hook calls.     file_test_reset();
  }

  /** * Tests the public file transfer system. */
  public function testPublicFileTransfer() {
    // Test generating a URL to a created file.     $file = $this->createFile();
    $url = $this->fileUrlGenerator->generateAbsoluteString($file->getFileUri());
    // URLs can't contain characters outside the ASCII set so $filename has to be     // encoded.     $filename = $GLOBALS['base_url'] . '/' . \Drupal::service('stream_wrapper_manager')->getViaScheme('public')->getDirectoryPath() . '/' . rawurlencode($file->getFilename());
    $this->assertEquals($filename$url, 'Correctly generated a URL for a created file.');
    $http_client = $this->getHttpClient();
    $response = $http_client->head($url);
    $this->assertEquals(200, $response->getStatusCode(), 'Confirmed that the generated URL is correct by downloading the created file.');

    // Test generating a URL to a shipped file (i.e. a file that is part of     // Drupal core, a module or a theme, for example a JavaScript file).     $filepath = 'core/assets/vendor/jquery/jquery.min.js';
    
'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');
    $this->drupalCreateNode($defaults + [
      'body' => [
        'value' => '<p><a href="' . $absolute_url . '">Absolute URL</a></p>',
        'format' => 'full_html',
      ],

  public function setFileUri($uri) {
    $this->get('uri')->value = $uri;
  }

  /** * {@inheritdoc} */
  public function createFileUrl($relative = TRUE) {
    /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    return $relative ? $file_url_generator->generateString($this->getFileUri()) : $file_url_generator->generateAbsoluteString($this->getFileUri());
  }

  /** * {@inheritdoc} */
  public function getMimeType() {
    return $this->get('filemime')->value;
  }

  /** * {@inheritdoc} */

    $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->assertSession()->statusCodeEquals(403);

      
    $this->drupalGet(substr_replace($nested_url_with_wrong_token, '//styles/', strrpos($nested_url_with_wrong_token, '/styles/')strlen('/styles/')));
    $this->assertSession()->statusCodeEquals(404);
    $this->drupalGet(substr_replace($nested_url_with_wrong_token, '////styles/', strrpos($nested_url_with_wrong_token, '/styles/')strlen('/styles/')));
    $this->assertSession()->statusCodeEquals(404);
    // Make sure the image can still be generated if a correct token is used.     $this->drupalGet($nested_url);
    $this->assertSession()->statusCodeEquals(200);

    // Check that requesting a nonexistent image does not create any new     // directories in the file system.     $directory = $scheme . '://styles/' . $this->style->id() . '/' . $scheme . '/' . $this->randomMachineName();
    $this->drupalGet(\Drupal::service('file_url_generator')->generateAbsoluteString($directory . '/' . $this->randomString()));
    $this->assertDirectoryDoesNotExist($directory);
  }

}
    // with the script path. If the file does not exist, use Url::fromUri() to     // ensure that it is included. Once the file exists it's fine to fall back     // to the actual file path, this avoids bootstrapping PHP once the files are     // built.     if ($clean_urls === FALSE && $stream_wrapper_manager::getScheme($uri) == 'public' && !file_exists($uri)) {
      $directory_path = $stream_wrapper_manager->getViaUri($uri)->getDirectoryPath();
      return Url::fromUri('base:' . $directory_path . '/' . $stream_wrapper_manager::getTarget($uri)['absolute' => TRUE, 'query' => $token_query])->toString();
    }

    /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    $file_url = $file_url_generator->generateAbsoluteString($uri);
    // Append the query string with the token, if necessary.     if ($token_query) {
      $file_url .= (str_contains($file_url, '?') ? '&' : '?') . UrlHelper::buildQuery($token_query);
    }

    return $file_url;
  }

  /** * {@inheritdoc} */
  
Home | Imprint | This part of the site doesn't use cookies.