function FileUrlGenerator::transformRelative

Same name and namespace in other branches
  1. 10 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()

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

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