henriqueramos / laravel_json_schema_validator
Laravel JSON Schema Validator 是一个 Composer 包,旨在帮助我们验证 JSON Schema。
1.0.4
2020-04-27 05:45 UTC
Requires
- php: >=7.3
- laravel/framework: >=5.8
- swaggest/json-schema: ^0.12.29
Requires (Dev)
- phpunit/php-code-coverage: ^7.0.9
- phpunit/phpunit: 8.5.4
- slevomat/coding-standard: ~4.0
- squizlabs/php_codesniffer: *
This package is auto-updated.
Last update: 2024-08-29 22:53:14 UTC
README
Laravel JSON Schema 验证器 是一个 Composer
包,用于将 JSON 对象与 JSON Schemas 进行验证,作为一个 Illuminate\Validation\Validator
定制规则。
关于
本包仅支持 Laravel 版本 >= 5.8
。以及 PHP 版本 >= 7.3
。
我们使用令人难以置信的包 swaggest/json-schema
作为依赖项,使一切 像魔法一样工作。
安装
将以下行添加到 composer.json
的 require
部分
{ "require": { "henriqueramos/laravel_json_schema_validator": "^1.0.0" } }
设置
- 运行
php artisan vendor:publish --provider="RamosHenrique\JsonSchemaValidator"
。这将为您在config
文件夹中创建一个名为json_schema_validator.php
的文件。 - 在您的
.env
文件中,添加您的 JSON Schema 文件存储路径,键为JSON_SCHEMA_VALIDATOR_STORAGE_PATH
(例如JSON_SCHEMA_VALIDATOR_STORAGE_PATH=storage/jsonschemas/
)。 - 设置您的 JSON Schema 文件
什么是 JSON Schema
我们支持以下 schema
以下是一个 JSON Schema 及其有效负载的示例
$schemaJson = <<<'JSON' { "type": "object", "properties": { "uuid": { "type": "integer" }, "userId": { "type": "integer" }, "items": { "type": "array", "minimum": 1, "items": { "$ref": "#/definitions/items" } } }, "required":[ "uuid", "userId", "items", ], "definitions": { "items": { "type": "object", "properties": { "id": { "type": "integer" }, "price": { "type": "number" }, "updated": { "type": "string", "format": "date-time" } }, "required":[ "id", "price" ] } } } JSON; $payload = <<<'JSON' { "uuid": 8, "userId": 1, "items": [ { "id": 12, "price": 49.90, "updated": "2020-09-07T20:20:39-03:00" }, { "id": 15, "price": 99, "updated": "2020-06-22T16:48:12-03:00" } ] } JSON;
使用方法
在您的选择存储路径上保存 JSON Schema 文件 后,您可以在您的 FormRequest
扩展类中使用它作为 验证规则。
<?php declare(strict_types = 1); namespace RamosHenrique\Requests; use Illuminate\Foundation\Http\FormRequest; class ValidatingPayloadRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize(): bool { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules(): array { return [ 'jsonData' => [ 'bail', 'required', 'json', 'json_schema_validator:validJSONSchema.json', ], ]; } /** * Custom messages for the route validator. * * @return array */ public function messages(): array { return [ 'expectedData.required' => 'required.jsonData', 'expectedData.json' => 'expectedData.needs.needs.to.be.a.valid.json', ]; } }