sintonia/legacy/application/common/OsPath.php

89 lines
2.2 KiB
PHP
Raw Normal View History

<?php
2021-10-11 16:10:47 +02:00
class Application_Common_OsPath
{
// this function is from http://stackoverflow.com/questions/2670299/is-there-a-php-equivalent-function-to-the-python-os-path-normpath
public static function normpath($path)
{
2021-10-11 16:10:47 +02:00
if (empty($path)) {
return '.';
2021-10-11 16:10:47 +02:00
}
if (strpos($path, '/') === 0) {
$initial_slashes = true;
2021-10-11 16:10:47 +02:00
} else {
$initial_slashes = false;
2021-10-11 16:10:47 +02:00
}
if (
2022-07-11 17:07:30 +02:00
$initial_slashes
2021-10-11 16:10:47 +02:00
&& (strpos($path, '//') === 0)
&& (strpos($path, '///') === false)
) {
$initial_slashes = 2;
2021-10-11 16:10:47 +02:00
}
$initial_slashes = (int) $initial_slashes;
2021-10-11 16:10:47 +02:00
$comps = explode('/', $path);
2021-10-11 16:10:47 +02:00
$new_comps = [];
foreach ($comps as $comp) {
if (in_array($comp, ['', '.'])) {
continue;
2021-10-11 16:10:47 +02:00
}
if (
2021-10-11 16:10:47 +02:00
($comp != '..')
|| (!$initial_slashes && !$new_comps)
|| ($new_comps && (end($new_comps) == '..'))
) {
array_push($new_comps, $comp);
2021-10-11 16:10:47 +02:00
} elseif ($new_comps) {
array_pop($new_comps);
2021-10-11 16:10:47 +02:00
}
}
$comps = $new_comps;
$path = implode('/', $comps);
2021-10-11 16:10:47 +02:00
if ($initial_slashes) {
$path = str_repeat('/', $initial_slashes) . $path;
2021-10-11 16:10:47 +02:00
}
if ($path) {
return $path;
2021-10-11 16:10:47 +02:00
}
return '.';
}
2021-10-11 16:10:47 +02:00
/* Similar to the os.path.join python method
* http://stackoverflow.com/a/1782990/276949 */
2021-10-11 16:10:47 +02:00
public static function join()
{
$args = func_get_args();
2021-10-11 16:10:47 +02:00
$paths = [];
2021-10-11 16:10:47 +02:00
foreach ($args as $arg) {
$paths = array_merge($paths, (array) $arg);
}
2021-10-11 16:10:47 +02:00
foreach ($paths as &$path) {
$path = trim($path, DIRECTORY_SEPARATOR);
}
if (substr($args[0], 0, 1) == DIRECTORY_SEPARATOR) {
$paths[0] = DIRECTORY_SEPARATOR . $paths[0];
}
return implode(DIRECTORY_SEPARATOR, $paths);
}
2021-10-11 16:10:47 +02:00
public static function formatDirectoryWithDirectorySeparators($dir)
{
2021-10-11 16:10:47 +02:00
if ($dir[0] != '/') {
$dir = '/' . $dir;
}
2021-10-11 16:10:47 +02:00
if ($dir[strlen($dir) - 1] != '/') {
$dir = $dir . '/';
}
2021-10-11 16:10:47 +02:00
return $dir;
}
}