function Filesystem::findShortestPath
Returns the shortest path from $from to $to
Parameters
bool $directories if true, the source/target are considered to be directories:
bool $preferRelative if true, relative paths will be preferred even if longer:
Return value
string
Throws
\InvalidArgumentException
1 call to Filesystem::findShortestPath()
- Filesystem::relativeSymlink in vendor/
composer/ composer/ src/ Composer/ Util/ Filesystem.php - Creates a relative symlink from $link to $target
File
-
vendor/
composer/ composer/ src/ Composer/ Util/ Filesystem.php, line 464
Class
- Filesystem
- @author Jordi Boggiano <j.boggiano@seld.be> @author Johannes M. Schmitt <schmittjoh@gmail.com>
Namespace
Composer\UtilCode
public function findShortestPath(string $from, string $to, bool $directories = false, bool $preferRelative = false) {
if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) {
throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to));
}
$from = $this->normalizePath($from);
$to = $this->normalizePath($to);
if ($directories) {
$from = rtrim($from, '/') . '/dummy_file';
}
if (\dirname($from) === \dirname($to)) {
return './' . basename($to);
}
$commonPath = $to;
while (strpos($from . '/', $commonPath . '/') !== 0 && '/' !== $commonPath && !Preg::isMatch('{^[A-Z]:/?$}i', $commonPath)) {
$commonPath = strtr(\dirname($commonPath), '\\', '/');
}
// no commonality at all
if (0 !== strpos($from, $commonPath)) {
return $to;
}
$commonPath = rtrim($commonPath, '/') . '/';
$sourcePathDepth = substr_count((string) substr($from, \strlen($commonPath)), '/');
$commonPathCode = str_repeat('../', $sourcePathDepth);
// allow top level /foo & /bar dirs to be addressed relatively as this is common in Docker setups
if (!$preferRelative && '/' === $commonPath && $sourcePathDepth > 1) {
return $to;
}
$result = $commonPathCode . substr($to, \strlen($commonPath));
if (\strlen($result) === 0) {
return './';
}
return $result;
}