function Filesystem::findShortestPathCode
Returns PHP code that, when executed in $from, will return the path 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
File
-
vendor/
composer/ composer/ src/ Composer/ Util/ Filesystem.php, line 516
Class
- Filesystem
- @author Jordi Boggiano <j.boggiano@seld.be> @author Johannes M. Schmitt <schmittjoh@gmail.com>
Namespace
Composer\UtilCode
public function findShortestPathCode(string $from, string $to, bool $directories = false, bool $staticCode = 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 ($from === $to) {
return $directories ? '__DIR__' : '__FILE__';
}
$commonPath = $to;
while (strpos($from . '/', $commonPath . '/') !== 0 && '/' !== $commonPath && !Preg::isMatch('{^[A-Z]:/?$}i', $commonPath) && '.' !== $commonPath) {
$commonPath = strtr(\dirname($commonPath), '\\', '/');
}
// no commonality at all
if (0 !== strpos($from, $commonPath) || '.' === $commonPath) {
return var_export($to, true);
}
$commonPath = rtrim($commonPath, '/') . '/';
if (str_starts_with($to, $from . '/')) {
return '__DIR__ . ' . var_export((string) substr($to, \strlen($from)), true);
}
$sourcePathDepth = substr_count((string) substr($from, \strlen($commonPath)), '/') + (int) $directories;
// allow top level /foo & /bar dirs to be addressed relatively as this is common in Docker setups
if (!$preferRelative && '/' === $commonPath && $sourcePathDepth > 1) {
return var_export($to, true);
}
if ($staticCode) {
$commonPathCode = "__DIR__ . '" . str_repeat('/..', $sourcePathDepth) . "'";
}
else {
$commonPathCode = str_repeat('dirname(', $sourcePathDepth) . '__DIR__' . str_repeat(')', $sourcePathDepth);
}
$relTarget = (string) substr($to, \strlen($commonPath));
return $commonPathCode . (\strlen($relTarget) > 0 ? '.' . var_export('/' . $relTarget, true) : '');
}