plutonium / stubs-generator
从任何PHP代码生成存根以供IDE补全和静态分析。
v0.10.0
2024-05-16 12:45 UTC
Requires
- php: ^7.3 || ^8.0 || ^8.1
- nikic/php-parser: ^4.10
- symfony/console: ^5.1 || ^6.0
- symfony/filesystem: ^5.0 || ^6.0
- symfony/finder: ^5.0 || ^6.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16 || ^3.12
- phpunit/phpunit: ^9.4
- vimeo/psalm: ^4.1
README
使用此工具生成任何PHP代码中定义的函数、类、接口和全局变量的存根声明。随后可以使用这些存根通过 PHPStan 或其他工具来方便IDE补全或静态分析。存根生成对于混合定义和副作用代码特别有用。
生成器基于nikic的 PHP-Parser,代码还依赖于几个 Symfony 组件。
欢迎以 问题 或拉取请求的形式进行贡献!
示例
想法是将这个
// source-file-1.php /** * @param string $bar * @return int */ function foo($bar) { return (int) $bar; } /** @var string */ $something = '123abc'; if ($something) { echo foo($something); } // source-file-2.php namespace MyNamespace; class MyClass extends MyParentClass { public function method(): string { return ''; } }
变成这个
// stubs.php namespace { /** * @param string $bar * @return int */ function foo($bar) { } /** @var string */ $something = '123abc'; } namespace MyNamespace { class MyClass extends MyParentClass { public function method(): string { } } }
命令行使用
安装
composer global require php-stubs/generator
获取目录中所有PHP文件的格式化存根
generate-stubs /path/to/my-library
您也可以传递多个目录或文件名,用空格分隔。所有存根将在输出中连接。
将存根写入文件(并在stdout中查看一些统计信息)
generate-stubs /path/to/my-library --out=/path/to/output.php
关于完整命令行选项
generate-stubs --help
在PHP中使用
安装
composer require php-stubs/generator
简单示例
// You'll need the Composer Autoloader. require 'vendor/autoload.php'; // You may alias the classnames for convenience. use StubsGenerator\{StubsGenerator, Finder}; // First, instantiate a `StubsGenerator\StubsGenerator`. $generator = new StubsGenerator(); // Then, create a `StubsGenerator\Finder` which contains // the set of files you wish to generate stubs for. $finder = Finder::create()->in('/path/to/my-library/'); // Now you may use the `StubsGenerator::generate()` method, // which will return a `StubsGenerator\Result` instance. $result = $generator->generate($finder); // You can use the `Result` instance to pretty-print the stubs. echo $result->prettyPrint(); // You can also use it to retrieve the PHP-Parser nodes // that represent the generated stub declarations. $stmts = $result->getStubStmts();
附加功能
您可以限制生成存根的符号类型集合
// This will only generate stubs for function declarations. $generator = new StubsGenerator(StubsGenerator::FUNCTIONS); // This will only generate stubs for class or interface declarations. $generator = new StubsGenerator(StubsGenerator::CLASSES | StubsGenerator::INTERFACES);
符号类型集合包括
StubsGenerator::FUNCTIONS
:函数声明。StubsGenerator::CLASSES
:类声明。StubsGenerator::TRAITS
:特性声明。StubsGenerator::INTERFACES
:接口声明。StubsGenerator::DOCUMENTED_GLOBALS
:全局变量,但仅限于有文档注释的。StubsGenerator::UNDOCUMENTED_GLOBALS
:全局变量,但仅限于没有文档注释的。StubsGenerator::GLOBALS
:包括文档化和未文档化的全局变量的快捷方式。StubsGenerator::CONSTANTS
:常量声明。StubsGenerator::DEFAULT
:包括除未文档化的全局变量之外的一切的快捷方式。StubsGenerator::ALL
:包括一切的快捷方式。