affinity4 / file
递归搜索给定目录的子(或父)目录中的文件,使用正则表达式模式或文件名
2.1.7
2022-06-03 15:36 UTC
Requires
- php: >=7.3
Requires (Dev)
- phpunit/php-code-coverage: ^9.2
- phpunit/phpunit: ^9.5
README
使用正则表达式模式或精确文件名查找文件。
特性
- 通过精确文件名或正则表达式模式在当前目录中搜索文件或文件
- 在当前目录和父目录中使用文件名或正则表达式模式搜索文件或文件
- 在当前目录和父目录中递归搜索文件或文件,使用文件名或正则表达式模式。
安装
Affinity4/File 通过 composer 提供
composer require affinity4/file
或者
{
"require": {
"affinity4/file": "^2.1"
}
}
用法
假设文件夹结构为
root
|-- files
| |-- config.yml
| |-- config.php
| |-- 00
| | |-- test00-01.php
| | |-- test00-01.yml
| | |-- test00-02.php
| | |-- test00-02.yml
| | |-- 01
| | | | |-- test01-01.php
| | | | |-- test01-01.yml
| | | | |-- test01-02.php
| | | | |-- test01-02.yml
| | | | |-- test01-03.php
| | | | |-- test01-03.yml
| | | | |-- 02
| | | | | |-- YOU-ARE-HERE
| | | | | |-- test02-01.html
| | | | | |-- test02-01.css
| | | | | |-- test02-01.json
| | | | | |-- test02-02.json
要查找多个文件,您可以在 find()
方法中使用以下分隔符 /, @, #, ~ 的正则表达式模式。然后通过链式调用 in()
方法从该目录开始搜索,并使用 get()
返回结果
$file = new Affinity4\File\File;
$results = $file->find('/^test[\d]{2}-[\d]{2}.json$/')->in(__DIR__)->get();
$results[0]->getPathname(); // root/files/00/01/02/test02-01.json
$results[1]->getPathname(); // root/files/00/01/02/test02-02.json
您还可以在当前目录中搜索,如果没有找到匹配的文件,可以通过在 in()
后链式调用 parent()
方法向上搜索一级
$file = new Affinity4\File\File;
$results = $file->find('/^test00-[\d]{2}.php$/')->in(__DIR__)->parent()->get();
$results[0]->getPathname(); // root/files/00/test00-01.php
$results[1]->getPathname(); // root/files/00/test00-02.php
您还可以在当前目录中搜索,如果没有找到匹配的文件,可以通过在 in()
后链式调用 parents()
方法搜索所有父目录
$file = new Affinity4\File\File;
$result = $file->find('config.yml')->in(__DIR__)->parents()->get();
$result->getPathname(); // root/files/config.yml
您还可以通过 get()
方法指定是否只想返回一个项目。这将返回数组中的第一个 SplFileInfo 对象,而不是包含一个 SplFileInfo 对象的数组。
$file = new Affinity4\File\File;
$result = $file->find('/^test[\d]{2}-[\d]{2}.php$/')->in(__DIR__)->parents()->get(1);
return $result->getPathname() // root/files/00/01/test01-01.php;
您还可以通过 get()
方法指定您想要返回的数组中的确切项目数量。只要数字大于一个,结果将是一个包含 SPLFileInfo
对象的数组
$file = new Affinity4\File\File;
$results = $file->find('/^test[\d]{2}-[\d]{2}.php$/')->in(__DIR__)->parents()->get(2);
$results[0]->getPathname(); // root/files/00/01/test01-01.php;
$results[1]->getPathname(); // root/files/00/01/test01-02.php;
测试
运行测试
vendor/bin/phpunit
许可证
(c) 2017 Luke Watts (Affinity4.ie)
本软件根据 MIT 许可证授权。有关完整的版权和许可信息,请查看与此源代码一起分发的 LICENSE 文件。