shockedplot7560 / generator
从任何PHP代码生成占位符,用于IDE自动完成和静态分析。
1.0.0
2023-09-13 16:29 UTC
Requires
- php: ^8.2
- nikic/php-parser: ^4.17
- symfony/console: ^6.3
- symfony/filesystem: ^6.3
- symfony/finder: ^6.3
Requires (Dev)
- friendsofphp/php-cs-fixer: ^v3.26
- phpunit/phpunit: ^10.3
- vimeo/psalm: ^5.15
This package is auto-updated.
Last update: 2024-09-13 18:37:33 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
您也可以传递多个目录或文件名,用空格分隔。所有占位符将连接到输出中。
将占位符写入文件(并在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
:包括一切的快捷方式。