public static function realpath($somePath, $shouldCheckExistence = false)
{
// Do not resolve empty string/false/arrays into the current path
if (!$somePath) {
return $somePath;
}
if (is_array($somePath)) {
return array_map(array(__CLASS__, __FUNCTION__), $somePath);
}
// Trick to get scheme name and path in one action. If no scheme, then there will be only one part
$components = explode('://', $somePath, 2);
list($pathScheme, $path) = isset($components[1]) ? $components : array(null, $components[0]);
// Optimization to bypass complex logic for simple paths (eg. not in phar archives)
if (!$pathScheme && ($fastPath = stream_resolve_include_path($somePath))) {
return $fastPath;
}
$isRelative = !$pathScheme && $path[0] !== '/' && $path[1] !== ':';
if ($isRelative) {
$path = getcwd() . DIRECTORY_SEPARATOR . $path;
}
// resolve path parts (single dot, double dot and double delimiters)
$path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
if (strpos($path, '.') !== false) {
$parts = explode(DIRECTORY_SEPARATOR, $path);
$absolutes = [];
foreach ($parts as $part) {
if ('.' == $part) {
continue;
} elseif ('..' == $part) {
array_pop($absolutes);
} else {
$absolutes[] = $part;
}
}
$path = implode(DIRECTORY_SEPARATOR, $absolutes);
}
if ($pathScheme) {
$path = "{$pathScheme}://{$path}";
}
if ($shouldCheckExistence && !file_exists($path)) {
return false;
}
return $path;
}