You are here

public function FileUrlGenerator::transformRelative in Drupal 9

Transforms an absolute URL of a local file to a relative URL.

May be useful to prevent problems on multisite set-ups and prevent mixed content errors when using HTTPS + HTTP.

Parameters

string $file_url: A file URL of a local file as generated by \Drupal\Core\File\FileUrlGenerator::generate().

bool $root_relative: (optional) TRUE if the URL should be relative to the root path or FALSE if relative to the Drupal base path.

Return value

string If the file URL indeed pointed to a local file and was indeed absolute, then the transformed, relative URL to the local file. Otherwise: the original value of $file_url.

Overrides FileUrlGeneratorInterface::transformRelative

2 calls to FileUrlGenerator::transformRelative()
FileUrlGenerator::doGenerateString in core/lib/Drupal/Core/File/FileUrlGenerator.php
Creates an absolute web-accessible URL string.
FileUrlGenerator::generate in core/lib/Drupal/Core/File/FileUrlGenerator.php
Creates a root-relative web-accessible URL object.

File

core/lib/Drupal/Core/File/FileUrlGenerator.php, line 198

Class

FileUrlGenerator
Default implementation for the file URL generator service.

Namespace

Drupal\Core\File

Code

public function transformRelative(string $file_url, bool $root_relative = TRUE) : string {

  // Unfortunately, we pretty much have to duplicate Symfony's
  // Request::getHttpHost() method because Request::getPort() may return NULL
  // instead of a port number.
  $request = $this->requestStack
    ->getCurrentRequest();
  $host = $request
    ->getHost();
  $scheme = $request
    ->getScheme();
  $port = $request
    ->getPort() ?: 80;

  // Files may be accessible on a different port than the web request.
  $file_url_port = parse_url($file_url, PHP_URL_PORT) ?? $port;
  if ($file_url_port != $port) {
    return $file_url;
  }
  if ('http' == $scheme && $port == 80 || 'https' == $scheme && $port == 443) {
    $http_host = $host;
  }
  else {
    $http_host = $host . ':' . $port;
  }

  // If this should not be a root-relative path but relative to the drupal
  // base path, add it to the host to be removed from the URL as well.
  if (!$root_relative) {
    $http_host .= $request
      ->getBasePath();
  }
  return preg_replace('|^https?://' . preg_quote($http_host, '|') . '|', '', $file_url);
}