wwwision / types-jsonschema
PHP类生成JSON Schema文件的工具,请参阅https://json-schema.fullstack.org.cn/
1.0.0
2024-02-29 16:17 UTC
Requires
- php: >=8.1
- webmozart/assert: ^1.11
- wwwision/types: ^1.2
Requires (Dev)
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.1
- roave/security-advisories: dev-latest
- squizlabs/php_codesniffer: ^4.0.x-dev
README
为wwwision/types包集成的工具,允许从PHP代码生成JSON Schema文件
用法
该包可以通过composer安装
composer require wwwision/types-jsonschema
使用它,您可以从PHP类创建JSON Schema
class Contact { public function __construct(public string $name, public int $age) {} } $schema = JSONSchemaGenerator::fromClass(Contact::class); $expected = <<<JSON { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "additionalProperties": false, "required": [ "name", "age" ] } JSON; assert(json_encode($schema, JSON_PRETTY_PRINT) === $expected);
高级模式
支持wwwision/types包的所有属性,以创建复杂的模式。
示例:复杂复合对象
#[StringBased] final class GivenName { private function __construct(public readonly string $value) {} } #[StringBased] final class FamilyName { private function __construct(public readonly string $value) {} } final class FullName { public function __construct( public readonly GivenName $givenName, public readonly FamilyName $familyName, ) {} } #[Description('honorific title of a person')] enum HonorificTitle { #[Description('for men, regardless of marital status, who do not have another professional or academic title')] case MR; #[Description('for married women who do not have another professional or academic title')] case MRS; #[Description('for girls, unmarried women and married women who continue to use their maiden name')] case MISS; #[Description('for women, regardless of marital status or when marital status is unknown')] case MS; #[Description('for any other title that does not match the above')] case OTHER; } #[Description('A contact in the system')] final class Contact { public function __construct( public readonly HonorificTitle $title, public readonly FullName $name, #[Description('Whether the contact is registered or not')] public bool $isRegistered = false, ) {} } $schema = JSONSchemaGenerator::fromClass(Contact::class); $expected = <<<JSON { "type": "object", "description": "A contact in the system", "properties": { "title": { "type": "string", "description": "honorific title of a person", "enum": [ "MR", "MRS", "MISS", "MS", "OTHER" ] }, "name": { "type": "object", "properties": { "givenName": { "type": "string" }, "familyName": { "type": "string" } }, "additionalProperties": false, "required": [ "givenName", "familyName" ] }, "isRegistered": { "type": "boolean", "description": "Whether the contact is registered or not" } }, "additionalProperties": false, "required": [ "title", "name" ] } JSON; assert(json_encode($schema, JSON_PRETTY_PRINT) === $expected);
贡献
许可证
请参阅LICENSE