uuf6429 / phpdoc-to-jsonschema
A PHPDoc to JsonSchema converter.
Fund package maintenance!
uuf6429
paypal.me/uuf6429
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
Convert PHPStan-style PHPDoc to JSON Schema.
💾 Installation
This package can be installed with Composer, simply run the following:
composer require uuf6429/phpdoc-to-jsonschema
Consider using --dev
if you intend to use this library during development only.
🚀 Usage
The following code:
<?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);
...results in something like:
{ "definitions": { "MyApp.Person": { "required": [ "name", "height" ], "properties": { "name": { "type": "string", "readOnly": true }, "height": { "type": "integer", "readOnly": true } }, "type": "object" } }, "$ref": "#\/definitions\/MyApp.Person" }
See also ExampleTest
for a more complex example.
📖 Documentation
The \uuf6429\PHPDocToJSONSchema\Converter
class exposes the following:
-
function convertType(\phpDocumentor\Reflection\Type $type, ?string $currentClass): \Swaggest\JsonSchema\Schema
Converts the provided PHPDoc type and returns its schema.$type
The PHPDoc type to be converted.$currentClass
The fully-qualified class name of the class where that type appeared, or null if wasn't a class (e.g. for functions).