xakepehok / path
文件系统路径导航工具
0.2.7
2024-01-10 14:45 UTC
Requires
- php: >=7.2.0
- ext-json: *
Requires (Dev)
- phpunit/phpunit: ^9.0
README
Path类帮助你轻松操作任何路径(Unix风格、Windows风格、URI路径),向上和向下导航,提取最后一个路径项,检测项目根目录等。这个库不与文件系统交互。它只是帮助你操作路径字符串。
安装
composer require xakepehok/path
路径操作
Unix风格路径
# Create path object with some path and define path separator. # If separator not defined, it will be detected from passed path string $path = new \XAKEPEHOK\Path\Path('/any/path/here'); # /any/path echo $path->up(); # /any/path/here/down_1/down_2 echo $path->down('down_1')->down('down_2'); # Ending or double slashes will be removed # /any/path/here/down_1/down_2 echo $path->down('/down_1/')->down('/down_2/'); # Empty down will be ignored # /any/path/here echo $path->down(''); # /any/path/here/down_1/down_2 echo $path->down('down_1/down_2'); # Backslash will be replaced by slash, because path already contain slash # /any/path/here/down_1/down_2 echo $path->down('down_1\down_2'); $subPath = new \XAKEPEHOK\Path\Path('dir_1/dir_2') # /any/path/here/dir_1/dir_2 echo $path->down($subPath); # /any/path/down_1/dir_1/dir_2 echo $path->up()->down('down_1/down_2')->up()->down($subPath);
Windows风格路径
$path = new \XAKEPEHOK\Path\Path('C:\\Windows'); # C:\ echo $path->up(); # C:\Windows\System32\drivers echo $path->down('System32')->down('drivers'); # Ending or double backslashes will be removed # C:\Windows\System32\drivers echo $path->down('\\System32\\')->down('\\drivers\\'); # C:\Windows\System32\drivers echo $path->down('System32\drivers'); # Slash will be replaced by backslash, because path already contain backslash # C:\Windows\System32\drivers\etc echo $path->down('System32/drivers\etc'); $subPath = new \XAKEPEHOK\Path\Path('Adobe/Photoshop') # C:\Windows\System32\drivers echo $path->down($subPath); # C:\Program Files\Adobe\Photoshop echo $path->up()->down('Program Files\\Microsoft')->up()->down($subPath);
URI路径(类似Unix风格路径)
$path = new \XAKEPEHOK\Path\Path('https://example.com/path'); # https://example.com echo $path->up(); # https://example.com/path/dir_1/dir_2 echo $path->down('dir_1')->down('dir_2'); # https://example.com/path/down_1/down_2 echo $path->down('down_1/down_2'); # Backslash will be replaced by slash, because path already contain slash # https://example.com/path/down_1/down_2 echo $path->down('down_1\down_2'); $subPath = new \XAKEPEHOK\Path\Path('dir_1/dir_2')
路径末尾
$path = new \XAKEPEHOK\Path\Path('/etc/nginx/nginx.conf'); # Return FileName object $filename = $path->end(); # nginx echo $filename->getName(false); //without extension # nginx.conf echo $filename->getName(true); //with extension # conf echo $filename->getExtension(); //extension # true echo $filename->hasExtension(); //bool true if file has extension
检测项目根路径
# Return you project root path (dir that contain composer's vendor dir). # Its detected by reflection of \Composer\Autoload\ClassLoader.php placement $path = \XAKEPEHOK\Path\Path::root();