Skip to content

Commit eaf3883

Browse files
committed
feat: add new fs method realpath
Signed-off-by: inhere <[email protected]>
1 parent 0af05eb commit eaf3883

File tree

3 files changed

+57
-1
lines changed

3 files changed

+57
-1
lines changed

src/FS.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Toolkit\FsUtil;
4+
5+
/**
6+
* Class FS
7+
*
8+
* @package Toolkit\FsUtil
9+
*/
10+
class FS extends FileSystem
11+
{
12+
13+
}

src/FileSystem.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ public static function pathModeInfo(string $filepath): int
258258
{
259259
/* 如果不存在,则不可读、不可写、不可改 */
260260
if (!file_exists($filepath)) {
261-
return false;
261+
return 0;
262262
}
263263

264264
$mark = 0;

src/Traits/FileSystemFuncTrait.php

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,21 @@
1313
use Toolkit\FsUtil\Exception\FileSystemException;
1414
use Toolkit\FsUtil\Exception\IOException;
1515
use Toolkit\Stdlib\Arr;
16+
use Toolkit\Stdlib\OS;
1617
use Traversable;
18+
use function array_filter;
19+
use function array_pop;
1720
use function copy;
1821
use function error_get_last;
1922
use function function_exists;
23+
use function implode;
2024
use function is_dir;
2125
use function mkdir;
26+
use function realpath;
2227
use function rmdir;
28+
use function str_replace;
2329
use function strlen;
30+
use const DIRECTORY_SEPARATOR;
2431

2532
/**
2633
* Trait FileSystemFuncTrait
@@ -148,6 +155,42 @@ public static function chown($files, string $user, $recursive = false): void
148155
}
149156
}
150157

158+
/**
159+
* @param string $path
160+
*
161+
* @return string
162+
* @see realpath()
163+
* @link https://www.php.net/manual/zh/function.realpath.php#84012
164+
*/
165+
public static function realpath(string $path): string
166+
{
167+
$path = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
168+
$parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
169+
if (!$parts) {
170+
return '';
171+
}
172+
173+
// ~: is user home dir in *nix OS
174+
if ($parts[0] === '~' && false === OS::isWindows()) {
175+
$parts[0] = OS::getUserHomeDir();
176+
}
177+
178+
$absolutes = [];
179+
foreach ($parts as $part) {
180+
if ('.' === $part) {
181+
continue;
182+
}
183+
184+
if ('..' === $part) {
185+
array_pop($absolutes);
186+
} else {
187+
$absolutes[] = $part;
188+
}
189+
}
190+
191+
return implode(DIRECTORY_SEPARATOR, $absolutes);
192+
}
193+
151194
/**********************************************************************************
152195
* dir functions
153196
*********************************************************************************/

0 commit comments

Comments
 (0)