function FileUrlGenerator::transformRelative

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/File/FileUrlGenerator.php \Drupal\Core\File\FileUrlGenerator::transformRelative()
  2. 11.x core/lib/Drupal/Core/File/FileUrlGenerator.php \Drupal\Core\File\FileUrlGenerator::transformRelative()

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 208

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();
  $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 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.
  $base_path = !$root_relative ? $request->getBasePath() : '';
  $host = preg_quote($host, '@');
  $port = preg_quote($port, '@');
  $base_path = preg_quote($base_path, '@');
  return preg_replace("@^https?://{$host}(:{$port})?{$base_path}(\$|/)@", '/', $file_url);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.