open-code-modeling/json-schema-to-php

解析 JSON 架构文件,并提供 API 以轻松从 JSON 架构生成代码。

0.3.0 2021-02-11 21:29 UTC

This package is auto-updated.

Last update: 2024-08-29 05:13:13 UTC


README

解析 JSON 架构并提供 API 以轻松从 JSON 架构生成代码。

安装

$ composer require open-code-modeling/json-schema-to-php --dev

使用

假设你有一个这样的 JSON 架构。

{
    "type": "object",
    "required": ["buildingId", "name"],
    "additionalProperties": false,
    "definitions": {
        "name": {
            "type": ["string", "null"]
        }
    },

    "properties": {
        "buildingId": {
            "type": "string",
            "pattern": "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$"
        },
        "name": {
            "$ref": "#/definitions/name"
        }
    }
}

从解析的 JSON 创建 TypeSet 定义

$decodedJson = \json_decode($jsonSchema, true);

$typeSet = Type::fromDefinition($decodedJson);

/** @var ObjectType $type */
$type = $typeSet->first();

$type->additionalProperties(); // false

$properties = $type->properties();

/** @var TypeSet $buildingIdTypeSet */
$buildingIdTypeSet = $properties['buildingId'];

/** @var StringType $buildingId */
$buildingId = $buildingIdTypeSet->first();

$buildingId->name(); // buildingId
$buildingId->type(); // string
$buildingId->pattern(); // ^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$
$buildingId->isRequired(); // true
$buildingId->isNullable(); // false

/** @var TypeSet $nameTypeSet */
$nameTypeSet = $properties['name'];

/** @var ReferenceType $name */
$name = $nameTypeSet->first();

$resolvedTypeSet = $name->resolvedType();

/** @var StringType $resolvedType */
$resolvedType = $resolvedTypeSet->first();

$resolvedType->name(); // name
$resolvedType->type(); // string
$resolvedType->isRequired(); // true
$resolvedType->isNullable(); // true

// ...

请参阅 OpenCodeModeling\JsonSchemaToPhp\Type 类和测试以获取更多信息。