uuf6429 / phpdoc-to-jsonschema
PHPDoc 到 JsonSchema 转换器。
1.0.1
2024-08-15 17:16 UTC
Requires
- php: ^8.1
- swaggest/json-schema: ^0.12.42
- uuf6429/phpstan-phpdoc-type-resolver: dev-main
Requires (Dev)
- ergebnis/composer-normalize: ^2.42
- friendsofphp/php-cs-fixer: ^3.53
- phpstan/phpstan: ^1.11
- phpunit/phpunit: ^10
- roave/security-advisories: dev-latest
README
将 PHPStan 风格的 PHPDoc 转换为 JSON Schema。
💾 安装
此包可以通过 Composer 安装,只需运行以下命令
composer require uuf6429/phpdoc-to-jsonschema
如果您打算仅在开发期间使用此库,请考虑使用 --dev
。
🚀 使用
以下代码
<?php namespace MyApp; // Define an example class to be featured in the json schema class Person { public function __construct( public readonly string $name, public readonly int $height, ) { } } // Load a PHPDoc block that should return an instance of the Person class $docblock = \uuf6429\PHPStanPHPDocTypeResolver\PhpDoc\Factory::createInstance() ->createFromComment('/** @return \MyApp\Person */'); // Retrieve the @return tag for that docblock. /** @var \PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode $returnTag */ $returnTag = $docblock->getTag('@return'); // Convert that @return tag to JSON Schema // (note that convertTag() takes typed tags, for example: @param, @var, @property[-read/-write] and of course @return) $converter = new \uuf6429\PHPDocToJSONSchema\Converter(); $result = $converter->convertType($returnTag->type, null); // Export the schema and print it out as json echo json_encode(\Swaggest\JsonSchema\Schema::export($result), JSON_PRETTY_PRINT);
...结果类似于
{ "definitions": { "MyApp.Person": { "required": [ "name", "height" ], "properties": { "name": { "type": "string", "readOnly": true }, "height": { "type": "integer", "readOnly": true } }, "type": "object" } }, "$ref": "#\/definitions\/MyApp.Person" }
有关更复杂的示例,请参阅 ExampleTest
。
📖 文档
\uuf6429\PHPDocToJSONSchema\Converter
类公开以下内容
-
function convertType(\phpDocumentor\Reflection\Type $type, ?string $currentClass): \Swaggest\JsonSchema\Schema
将提供的 PHPDoc 类型转换为 schema。$type
要转换的 PHPDoc 类型。$currentClass
出现该类型的类的完全限定类名,如果该类型不是类(例如,对于函数),则为 null。