jdesrosiers / silex-json-schema-provider
一个用于处理 JSON Schema 的 Silex 服务提供者
v1.0.1
2018-04-24 02:25 UTC
Requires
- geraintluff/jsv4: ~1.0
- silex/silex: ~2.0
Requires (Dev)
- phpunit/phpunit: ~4.5
- symfony/browser-kit: ~2.6
This package is auto-updated.
Last update: 2024-08-26 03:03:20 UTC
README
silex-json-schema-provider 是一个用于处理 JSON Schema 的 Silex 服务提供者。
安装
使用 composer 安装 silex-json-schema-provider。本项目使用 sematic versioning。
composer require jdesrosiers/silex-json-schema-provider "~1.0"
参数
- json-schema.correlationMechanism: ("profile" 或 "link") 默认为 "link"。
- json-schema.describedBy: (字符串) 一个 URI,用于标识描述响应的 Schema 的位置。
服务
- json-schema.schema-store: 一个 SchemaStore 的实例,如这里所述 https://github.com/geraintluff/jsv4-php。
- json-schema.validator: 一个对象,公开了这里描述的 Jsv4 方法 https://github.com/geraintluff/jsv4-php。
注册
$app->register(new JDesrosiers\Silex\Provider\JsonSchemaServiceProvider());
JSON 验证
JSON Schema 验证由 https://github.com/geraintluff/jsv4-php 支持。
$schemaJson = <<<SCHEMA { "$schema": "https://json-schema.fullstack.org.cn/draft-04/hyper-schema#", "type": "object", "properties": { "id": { "type": "string" } } } SCHEMA; $app["json-schema.schema-store"]->add("/schema/foo", json_decode($schemaJson)); $schema = $app["json-schema.schema-store"]->get("/schema/foo"); $validation = $app["json-schema.validator"]->validate($data, $schema);
关联
JSON Schema 规范有两个建议用于关联一个 Schema 到资源。此服务提供者在支持两者的中间件之后注册。有关 Schema 关联的更多信息,请参阅 https://json-schema.fullstack.org.cn/latest/json-schema-core.html#anchor33。设置 $app["json-schema.describedBy"]
参数为响应应关联的 Schema。
$app->get("/foo/{id}", function ($id) use ($app) { $app["json-schema.describedBy"] = "/schema/foo"; return JsonResponse::create(array("id" => $id)); });
完整示例
$app["json-schema.schema-store"]->add("/schema/foo", $app["schemaRepository"]->fetch("foo")); $app->put("/foo/{id}", function (Request $request, $id) use ($app) { $data = json_decode($request->getContent()); $schema = $app["json-schema.schema-store"]->get("/schema/foo"); $validation = $app["json-schema.validator"]->validate($data, $schema); if (!$validation->valid) { $error = array("validationErrors" => $validation->errors); return JsonResponse::create($error, Response::HTTP_BAD_REQUEST); } $isCreated = !$app["fooRepository"]->contains($id); $app["fooRepository"]->save($id, $data); $app["json-schema.describedBy"] = "/schema/foo"; return JsonResponse::create($data, $isCreated ? Response::HTTP_CREATED : Response::HTTP_OK); });