You are here

private static function UriResolver::getRelativePath in Lockr 7.3

1 call to UriResolver::getRelativePath()
UriResolver::relativize in vendor/guzzlehttp/psr7/src/UriResolver.php
Returns the target URI as a relative reference from the base URI.

File

vendor/guzzlehttp/psr7/src/UriResolver.php, line 182

Class

UriResolver
Resolves a URI reference in the context of a base URI and the opposite way.

Namespace

GuzzleHttp\Psr7

Code

private static function getRelativePath(UriInterface $base, UriInterface $target) {
  $sourceSegments = explode('/', $base
    ->getPath());
  $targetSegments = explode('/', $target
    ->getPath());
  array_pop($sourceSegments);
  $targetLastSegment = array_pop($targetSegments);
  foreach ($sourceSegments as $i => $segment) {
    if (isset($targetSegments[$i]) && $segment === $targetSegments[$i]) {
      unset($sourceSegments[$i], $targetSegments[$i]);
    }
    else {
      break;
    }
  }
  $targetSegments[] = $targetLastSegment;
  $relativePath = str_repeat('../', count($sourceSegments)) . implode('/', $targetSegments);

  // A reference to am empty last segment or an empty first sub-segment 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.
  if ('' === $relativePath || false !== strpos(explode('/', $relativePath, 2)[0], ':')) {
    $relativePath = "./{$relativePath}";
  }
  elseif ('/' === $relativePath[0]) {
    if ($base
      ->getAuthority() != '' && $base
      ->getPath() === '') {

      // In this case an extra slash is added by resolve() automatically. So we must not add one here.
      $relativePath = ".{$relativePath}";
    }
    else {
      $relativePath = "./{$relativePath}";
    }
  }
  return $relativePath;
}