function Helper::getCanonicalPath

Resolves all dots, slashes and removes spaces after or before a path...

Parameters

string $path Input string:

Return value

string Canonical path, always without trailing slash

File

misc/typo3/phar-stream-wrapper/src/Helper.php, line 120

Class

Helper
Helper provides low-level tools on file name resolving. However it does not (and should not) maintain any runtime state information. In order to resolve Phar archive paths according resolvers have to be used.

Namespace

TYPO3\PharStreamWrapper

Code

private static function getCanonicalPath($path) {
  $path = static::normalizeWindowsPath($path);
  $absolutePathPrefix = '';
  if (static::isAbsolutePath($path)) {
    if (static::isWindows() && strpos($path, ':/') === 1) {
      $absolutePathPrefix = substr($path, 0, 3);
      $path = substr($path, 3);
    }
    else {
      $path = ltrim($path, '/');
      $absolutePathPrefix = '/';
    }
  }
  $pathParts = explode('/', $path);
  $pathPartsLength = count($pathParts);
  for ($partCount = 0; $partCount < $pathPartsLength; $partCount++) {
    // double-slashes in path: remove element
    if ($pathParts[$partCount] === '') {
      array_splice($pathParts, $partCount, 1);
      $partCount--;
      $pathPartsLength--;
    }
    // "." in path: remove element
    if ((isset($pathParts[$partCount]) ? $pathParts[$partCount] : '') === '.') {
      array_splice($pathParts, $partCount, 1);
      $partCount--;
      $pathPartsLength--;
    }
    // ".." in path:
    if ((isset($pathParts[$partCount]) ? $pathParts[$partCount] : '') === '..') {
      if ($partCount === 0) {
        array_splice($pathParts, $partCount, 1);
        $partCount--;
        $pathPartsLength--;
      }
      elseif ($partCount >= 1) {
        // Rremove this and previous element
        array_splice($pathParts, $partCount - 1, 2);
        $partCount -= 2;
        $pathPartsLength -= 2;
      }
      elseif ($absolutePathPrefix) {
        // can't go higher than root dir
        // simply remove this part and continue
        array_splice($pathParts, $partCount, 1);
        $partCount--;
        $pathPartsLength--;
      }
    }
  }
  return $absolutePathPrefix . implode('/', $pathParts);
}

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