griffin/harpy

在 PHP 源代码中搜索类名

1.0.2 2021-05-11 16:23 UTC

This package is auto-updated.

Last update: 2024-09-11 23:28:52 UTC


README

在 PHP 源代码中搜索类名

Build Status Latest Stable Version Codecov License

描述

Harpy 是一个用于在 PHP 源代码中搜索类名的微库,它使用模式来查找文件,并解析这些文件以检索所有定义的类。

该库是 Griffin 项目 的一部分。

安装

此包默认使用 Composer 作为存储库。您可以通过在 composer.jsonrequire 部分中添加包名来安装它,指向最新的稳定版本。

{
  "require": {
    "griffin/harpy": "^1.0"
  }
}

使用方法

Griffin\Harpy\Harpy::search 方法使用表示文件或目录的 string 变量的可变参数。这些目录将被递归列出以查找文件。每个找到的文件都将被解析以查找类定义。

use Griffin\Harpy\Harpy;

$harpy = new Harpy();

$classnames = $harpy->search(
    // Files
    './src/Harpy.php',
    './tests/HarpyTest.php',
    // Directories
    './src',
    './tests',
);

var_dump($classnames);

/*
array(6) {
  [0]=>
  string(19) "Griffin\Harpy\Harpy"
  [1]=>
  string(27) "GriffinTest\Harpy\HarpyTest"
  [2]=>
  string(20) "Griffin\Harpy\Finder"
  [3]=>
  string(20) "Griffin\Harpy\Parser"
  [4]=>
  string(28) "GriffinTest\Harpy\FinderTest"
  [5]=>
  string(28) "GriffinTest\Harpy\ParserTest"
}
 */

如果 Harpy 没有权限列出目录或读取文件,则不会引发警告,因为它只搜索类而不处理错误。此外,Harpy 不是一个类加载器,您必须使用类似 Composer 的工具来执行此任务。

示例

一个示例是从目录中检索所有类并在类实现特定接口时初始化一个对象。

use FooBar\ExampleInterface;
use Griffin\Harpy\Harpy;

$objects    = [];
$classnames = (new Harpy())->search('src');

foreach ($classnames as $classname) {
    if (is_subclass_of($classname, ExampleInterface::class, true /* allow string */)) {
        $objects[] = new $classname();
    }
}

开发

您可以使用 Docker Compose 来构建映像并运行容器以开发和测试此包。

docker-compose build
docker-compose run --rm php composer install
docker-compose run --rm php composer test

参考

许可证

此包是开源的,可在 MIT 许可证下使用,该许可证描述在 LICENSE 中。