programster/json-schema-creator

一个PHP包,用于简化创建JSON模式。

1.2.0 2021-07-08 15:41 UTC

This package is auto-updated.

Last update: 2024-09-08 22:52:21 UTC


README

JSON Schema Creator 这是一个简单的PHP包,可以快速轻松地生成可以用于验证和文档的JSON模式。

这个工具主要是在opis.io/json-schema的JSON模式文档的帮助下构建的。

安装

composer require programster/json-schema-creator

示例

<?php
require_once(__DIR__ . '/../vendor/autoload.php');

$name = new \Programster\JsonSchema\Types\StringType(name: "product_name", minLength: 3);
$barcode = new \Programster\JsonSchema\Types\StringType(name: "barcode", minLength: 12);
$description = new \Programster\JsonSchema\Types\StringType(name: "description", minLength: 12);

$requiredProperties = array(
    $name,
    $barcode,
);

$nonRequiredProprties = array(
    $description
);

$object = new Programster\JsonSchema\Types\ObjectType(
    "Product",
    new Programster\JsonSchema\PropertyCollection(...$requiredProperties, ...$nonRequiredProprties),
    new Programster\JsonSchema\RequiredPropertiesCollection(...$requiredProperties)
);

$schema = new \Programster\JsonSchema\Schema($object, "Product Schema", "A product definition");
print($schema) . PHP_EOL;

这将生成以下模式

{
    "$schema": "https://json-schema.fullstack.org.cn/draft-07/schema#",
    "$id": "Product Schema",
    "title": "A product definition",
    "name": "Product",
    "type": "object",
    "properties": {
        "product_name": {
            "type": "string",
            "minLength": 3
        },
        "barcode": {
            "type": "string",
            "minLength": 12
        },
        "description": {
            "type": "string",
            "minLength": 12
        }
    },
    "required": [
        "product_name",
        "barcode"
    ]
}

测试

您可以使用jsonschemalint.com检查您生成的模式是否有效