uuf6429/phpdoc-to-jsonschema

A PHPDoc to JsonSchema converter.

1.0.1 2024-08-15 17:16 UTC

This package is auto-updated.

Last update: 2024-10-15 17:37:51 UTC


README

CI Coverage Minimum PHP Version License Latest Stable Version Latest Unstable Version

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).