onlinesid / json-schema-provider
Json Schema Silex 服务提供者
v0.2
2019-03-19 23:29 UTC
Requires
- php: >=5.6.0
- justinrainbow/json-schema: ~5.2
- silex/silex: >=2.0
Requires (Dev)
- phpunit/phpunit: ~4.8
This package is auto-updated.
Last update: 2024-09-20 11:35:10 UTC
README
Json Schema Silex 服务提供者
和验证工具
一个用于验证 JSON
数据与给定 Schema
的 Silex 服务提供者。
安装
库
$ git clone https://github.com/onlinesid/json-schema-provider.git
依赖
Composer
(将使用 Composer 类加载器)
$ wget https://getcomposer.org.cn/composer.phar
$ php composer.phar require onlinesid/json-schema-provider:dev-master
使用
注册服务提供者
$app->register(new OnlineSid\Silex\Provider\JsonSchema\ServiceProvider(), array( 'json-schema.options' => array( 'json_schema_dir' => __DIR__.'/public/json-schema/', 'json_message_dir' => __DIR__.'/public/json-message/', 'default_json_message' => 'default.json', ), ));
json_schema_dir
: 存储json schema文件的目录json_message_dir
: 存储自定义错误信息的json文件的目录default_json_message
: 存储默认错误信息的json文件,文件必须位于json_message_dir
目录下
在控制器中使用
$validator = $this->app['json-schema-validator']; $validation_result = $validator->validate(array( 'request' => $this->request->get('booking'), // array to validate 'json_schema' => 'booking.json', // under json_schema_dir 'json_message' => 'booking.json', // under json_message_dir )); // check $validation_result->isValid() to see if validation pass or fail
####json-schema/booking.json 请参阅json-schema获取更多详情。
这是包含约束/规则的json schema
{ "type": "object", "properties": { "first_name": { "type": "string", "required": true, "maxLength": 100 }, "last_name": { "type": "string", "required": true, "maxLength": 100 } } }
####json-message/booking.json 您可以指定自己的自定义错误信息。
{ "first_name": { "label": "First name", "messages": { "required": "{{ label }} is required.", "maxLength": "{{ label }} must not be more than {{ schema.maxLength }} characters long." } }, "last_name": { "label": "Last name", "messages": { "required": "{{ label }} is required.", "maxLength": "{{ label }} must not be more than {{ schema.maxLength }} characters long." } } }
####json-message/default.json 您可以指定全局默认错误信息(例如:不是按字段而是按约束规则类型)
{ "messages": { "required": "Required field.", "minLength": "Must be {{ schema.minLength }} chars or more.", "maxLength": "Must not be more than {{ schema.maxLength }} chars.", "pattern": "Incorrect format" } }
运行测试
$ phpunit