phindmarsh / statham
JSON Schema 验证器
v1.0.2
2023-05-18 21:22 UTC
This package is not auto-updated.
Last update: 2024-09-12 06:36:34 UTC
README
用 PHP 编写的 JSON Schema 验证器
这是一个(几乎是直接)将用于验证 JSON 对 JSON schema 的 JavaScript 库 ZSchema 转移到 PHP 的例子,用于验证 JSON schema 本身。
原因
编写此代码的动机是为了在 PHP 中验证 swagger.io 文件,现有的验证器都无法处理递归的 schema,也无法正确解析嵌套的引用。JavaScript 验证器按照我的需求工作,所以我将其移植过来。
因此 Statham 将
- 在验证引用自身的 schema 时不无限递归
- 正确处理位于不同 schema 中的 $refs
使用方法
// schemas used during validation $schemas = [ "https://json-schema.fullstack.org.cn/draft-04/schema#" "https://swagger.org.cn/v2/schema.json#" ]; $statham = new \Statham\Statham(); // download each schema and add to internal cache foreach($schemas as $schema_url){ $schema = json_decode(file_get_contents($schema_url)); $statham->setRemoteReference($schema_url, $schema); } // just validate the schema (no data) $statham->validateSchema($schemas[1]); // validate $json_to_validate against a given schema $statham->validate($json_to_validate, $schemas[1]);
Statham 不会自动下载外部引用的 schema(它完全可以,但是有原因),所以对于在验证过程中使用的任何 schema,请使用 $statham->setRemoteReference($url, $schema_object)
。
schema 可以作为对象传递(不支持作为数组传递的 schema,但完全可以),或者如果您已经使用了 $statham->setRemoteReference()
,您也可以将其作为字符串传递,即为 schema 的 URL。
JSON 数据只能作为对象传递,所以只需使用 json_decode($json)
(没有第二个 true
参数)即可。
待办事项
它没有正确检查格式(因此,电子邮件、日期等不是字符串以外的任何内容)。这很容易做到,但我还没有做。