tasoft / tools-path
用于操作虚拟路径的简单库
v1.5.8
2023-02-06 08:00 UTC
Requires
- php: >=7.2
Requires (Dev)
- phpunit/phpunit: ^9
This package is auto-updated.
Last update: 2024-09-06 11:24:11 UTC
README
这个PHP库是一个用于管理虚拟路径的小型工具。
虚拟路径是不需要在文件系统中存在的路径。
这导致了识别路径是目录还是文件的问题。
为了解决这个问题,该库使用以下标记声明虚拟路径
- 以
/开头的路径是零路径或绝对路径。 - 以
/结尾的路径是目录 - 组件
..是父目录 - 组件
.是当前目录 - 空组件将被忽略(例如:
/path///to/file.txt=>/path/to/file.txt)
因此,Path Tool提供了两种方法来确定路径是否为零路径或目录
use TASoft\Util\PathTool; PathTool::isZeroPath("/my/path"); // TRUE PathTool::isZeroPath("../path/"); // FALSE PathTool::isDirectory("my/path/to/"); // TRUE PathTool::isDirectory("/my/path.txt"); // FALSE PathTool::isDirectory("/my/path.txt/"); // TRUE
PathTool 的核心是 yieldPathComponents 方法。它为其他方法提供路径组件。您也可以使用以下描述的选项直接使用它
- OPTION_RESOLVE: 解析空目录、父目录和当前目录。
- OPTION_DENY_OUT_OF_BOUNDS: 不允许选择根目录的父目录(例如:
/root/path/../../../) - OPTION_YIELD_ROOT: 如果是零路径,则将
/作为第一个组件输出。 - OPTION_YIELD_COMPONENT: 输出 PathComponent 对象而不是字符串。
- OPTION_ALL: 包含之前描述的所有选项。
// Use bitwise operators to join options: $options = PathTool::OPTION_RESOLVE | PathTool::OPTION_YIELD_ROOT; // Or subtract them $options = PathTool::OPTION_ALL & ~PathTool::OPTION_DENY_OUT_OF_BOUNDS & ~PathTool::OPTION_YIELD_ROOT;
用法
use TASoft\Util\PathTool; // Normalize echo PathTool::normalize("/my/path/./to////oops/../../file.txt"); // /my/path/file.txt echo PathTool::normalize("/path/../../"); // Fails! // Out of bounds! ^^ echo PathTool::normalize("path/../../"); // ../ // Relative // Works only with zero paths! echo PathTool::relative("/my/dir/1/", "/my/dir/1/file.txt"); // file.txt echo PathTool::relative("/my/dir/1/", "my/dir/1/file.txt"); // Fails! // not a zero path ^ echo PathTool::relative("/my/dir/1", "/my/dir/2"); // 2 (because /my/dir/1 is a file) echo PathTool::relative("/my/dir/1/", "/my/dir/2"); // ../2 echo PathTool::relative("/my/dir/1", "/my/dir/2/"); // 2/ echo PathTool::relative("/my/dir/1/", "/my/dir/2/"); // ../2/ echo PathTool::relative("/path/file.txt", "/path/file.txt"); // "" echo PathTool::relative("/path/file.txt", "/path/"); // ./
真实路径工具
RealPathTool 允许对真实文件和目录执行简单任务,如迭代内容。
<?php use TASoft\Util\RealPathTool as Tool;