mperusso / php-stubs-generator
从任何PHP代码生成占位符,用于IDE自动完成和静态分析。
v0.8.4
2024-02-28 17:34 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-28 18:58:34 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:包括所有内容的快捷方式。