everlution / json-schema

此包最新版本(v1.0.2)没有可用的许可证信息。

在PHP中创建和验证JSON Schema

v1.0.2 2019-05-10 12:26 UTC

This package is auto-updated.

Last update: 2024-09-11 01:26:16 UTC


README

一个用于在PHP中创建和验证JSON Schema的库。

您不需要编写任何JSON字符串。

安装

composer require everlution/json-schema

JSON Schema定义

我们不是直接在JSON中编写JSON Schema,而是创建一个新的PHP类,其中包含编写较少的辅助工具。

<?php

namespace App\JsonSchema;

use Everlution\JsonSchema\AbstractJsonSchema;

class JwtTokensRequestJsonSchema extends AbstractJsonSchema
{
    public function toArray(): array
    {
        $data = [
            'title' => 'JWT Token Request',
            'description' => 'Get a new token',
            'type' => 'object',
            'properties' => [
                'key' => [
                    'type' => 'string',
                ],
                'secret' => [
                    'type' => 'string',
                ],
                // you can use helpers like this to reduce the amount of code to write and reduce mistakes
                // 'whateverString' => $this->getTypeString(?bool $nullable, ?int $minLength, ?int $maxLength, ?string $pattern, ?string $format)
            ],
        ];
        
        // on this level add "additionalProperties": false
        $this->addAdditionalPropertiesFalse($data);
        // same as above but recursively in every sub level
        $this->addAdditionalPropertiesFalseRecursive($data);
        
        // on this level add "required": [...] for all the defined properties
        $this->makeAllPropertiesRequired($data);
        // same as above but recursively in every sub level
        $this->makeAllPropertiesRequiredRecursive($data);
        
        return $data;
    }
}

然后我们可以使用以下方法生成实际的JSON Schema:

use App\JsonSchema\JwtTokensRequestJsonSchema;

$jsonSchema = new JwtTokensRequestJsonSchema();

$jsonSchemaString = $jsonSchema->generate();

针对数据的JSON Schema验证

该库提供了Everlution\JsonSchema\Validator\ValidatorInterface以及由justinrainbow/json-schema库实现的其实例。

您可以通过实现该接口添加自己的验证器。

use App\JsonSchema\JwtTokensRequestJsonSchema;
use Everlution\JsonSchema\Validator\DefaultValidator;
use Everlution\JsonSchema\Validator\ValidatorException;
use JsonSchema\Validator as JustinrainbowJsonSchema;

$jsonSchema = new JwtTokensRequestJsonSchema();

$validator = new DefaultValidator(new JustinrainbowJsonSchema());

$data = [
    'key' => '123132',
    'secret' => '123213',
];

try {
    // validate() throws an exception only when the data cannot be validated against the JSON Schema
    $validator->validate($jsonSchema, $data);
} catch (ValidatorException $e) {
    var_dump($e->getErrors());
}