php-stubs / generator
从任何PHP代码生成存根,以支持IDE自动补全和静态分析。
v0.8.4
2023-07-24 16:33 UTC
Requires
- php: ^7.3 || ^8.0
- 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
This package is auto-updated.
Last update: 2024-09-09 16:54:46 UTC
README
使用此工具生成任何PHP代码中定义的函数、类、接口和全局变量的存根声明。存根可以随后通过PHPStan或可能的其他工具来简化IDE自动补全或静态分析。对于定义与副作用混合的代码,存根生成特别有用。
生成器基于nikic的PHP-Parser,代码还依赖于几个Symfony组件。
欢迎通过问题或Pull Requests形式贡献!
示例
思路是将这个
// 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
您也可以传入多个目录或文件名,通过空格分隔。所有存根将连接到输出中。
将存根写入文件(并在标准输出中查看一些统计信息)
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
:包括所有内容的快捷方式。