You are here

public static function UrlGenerator::getRelativePath in Zircon Profile 8.0

Same name and namespace in other branches
  1. 8 vendor/symfony/routing/Generator/UrlGenerator.php \Symfony\Component\Routing\Generator\UrlGenerator::getRelativePath()

Returns the target path as relative reference from the base path.

Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash. Both paths must be absolute and not contain relative parts. Relative URLs from one resource to another are useful when generating self-contained downloadable document archives. Furthermore, they can be used to reduce the link size in documents.

Example target paths, given a base path of "/a/b/c/d":

  • "/a/b/c/d" -> ""
  • "/a/b/c/" -> "./"
  • "/a/b/" -> "../"
  • "/a/b/c/other" -> "other"
  • "/a/x/y" -> "../../x/y"

Parameters

string $basePath The base path:

string $targetPath The target path:

Return value

string The relative target path

2 calls to UrlGenerator::getRelativePath()
UrlGenerator::doGenerate in vendor/symfony/routing/Generator/UrlGenerator.php
UrlGeneratorTest::testGetRelativePath in vendor/symfony/routing/Tests/Generator/UrlGeneratorTest.php
@dataProvider provideRelativePaths

File

vendor/symfony/routing/Generator/UrlGenerator.php, line 306

Class

UrlGenerator
UrlGenerator can generate a URL or a path for any route in the RouteCollection based on the passed parameters.

Namespace

Symfony\Component\Routing\Generator

Code

public static function getRelativePath($basePath, $targetPath) {
  if ($basePath === $targetPath) {
    return '';
  }
  $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
  $targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath);
  array_pop($sourceDirs);
  $targetFile = array_pop($targetDirs);
  foreach ($sourceDirs as $i => $dir) {
    if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
      unset($sourceDirs[$i], $targetDirs[$i]);
    }
    else {
      break;
    }
  }
  $targetDirs[] = $targetFile;
  $path = str_repeat('../', count($sourceDirs)) . implode('/', $targetDirs);

  // A reference to the same base directory or an empty subdirectory must be prefixed with "./".
  // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
  // as the first segment of a relative-path reference, as it would be mistaken for a scheme name
  // (see http://tools.ietf.org/html/rfc3986#section-4.2).
  return '' === $path || '/' === $path[0] || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos) ? "./{$path}" : $path;
}