loilo/find-up

通过遍历祖先目录来查找文件

1.2.0 2019-08-28 20:52 UTC

This package is auto-updated.

Last update: 2024-09-24 07:52:40 UTC


README

FindUp logo: a folder icon with an upwards arrow in front

FindUp

Tests Version on packagist.org

通过遍历祖先目录来查找文件(例如,从项目内部查找 composer.json)。

安装

composer require loilo/find-up

使用方法

基本示例

/var/www
└── project
    ├── composer.json
    └── src
        └── foo
            ├── bar
            └── example.php

example.php:

use Loilo\FindUp\Up;

// Get the project's composer.json's path by
// walking up from /var/www/project/src/foo
Up::find('composer.json') === '/var/www/project/composer.json';

这是使用此包的最基本示例。查找器将从调用 Up::find() 的目录开始查找 composer.json 文件(即 /var/www/project/src/foo)。

注意:如果向上没有找到 composer.json,则 find 方法将返回 null

起始目录

如上基本示例所示,默认起始目录是调用 Up::find() 的目录。或者,可以将起始目录作为第二个参数传递给 find 方法。

// Start from the current working directory
Up::find('composer.json', getcwd());

高级匹配

除了要搜索的文件名外,还可以将(非字符串)可调用对象作为 find 方法的第一个参数传递。它将接收在向上的过程中遇到的每个文件,并决定它是否是要搜索的文件。

假设我们从上面基本示例目录树中的 example.php 开始,我们可以通过以下调用找到 composer.json 的路径

Up::find(function ($file, $directory) {
  return $file === 'composer.json';
});

提前停止搜索

您可以在达到文件系统根之前停止搜索,通过返回一个 Up::stop() 调用。例如,如果您知道您的 composer.json 不在从 /var/www 文件夹向上查找的情况下存在,您可以退出搜索。

Up::find(function ($file, $directory) {
  if ($directory === '/var/www') {
    return Up::stop();
  }

  return $file === 'composer.json';
});

返回 Up::stop() 时,默认情况下 Up::find() 方法将返回 null

但是,您可以为 stop() 方法传递一个路径,该路径将被用作结果。如果路径不是绝对路径,它将相对于当前 $directory 解析。

Up::find(function ($file, $directory) {
  if ($directory === '/var/www') {
    return Up::stop('stop.txt');
  }

  return false;
}) === '/var/www/stop.txt';

注意:在以前的版本中,停止搜索的方法是返回 Up::STOP 常量。

此技术仍然有效,但它已弃用,建议使用 Up::stop() 代替。

跳过文件夹

如果您确定某个目录不包含要搜索的文件,您可以通过返回 Up::skip() 来避免遍历所有文件。

Up::find(function ($file, $directory) {
  // Skip "src" directories
  if (basename($directory) === 'src') {
    return Up::skip();
  }

  return $file === 'composer.json';
});

默认情况下,Up::skip() 方法只会跳过当前扫描的目录。但是,您可以传递一个(正数)指示要跳过的目录层数。

...

// skip the current directory and its parent directory,
// continue with grandparent directory
return Up::skip(2)

注意:在以前的版本中,跳过扫描文件夹的方法是返回 Up::SKIP 常量。

此技术仍然有效,但它已弃用,建议使用 Up::skip() 代替。

跳转到其他文件夹

如果您想完全停止搜索当前目录树并从另一个路径继续,可以返回一个 Up::jump() 调用。

Up::find(function ($file, $directory) {
  if ($directory === '/var/www/project') {
    return Up::jump('/var/www/other-project');
  }

  return $file === 'composer.json';
});

注意:您只能跳转到当前搜索中尚未访问过的目录。这有助于避免无限循环。