jsonschema - 如何使用 JustinRainbow/JsonSchema 正确验证对象数组
问题描述
我有代码可以正确验证从返回单个文章的端点返回的文章。我很确定它工作正常,因为当我故意不在文章中包含必填字段时,它会给出验证错误。
我也有这段代码尝试验证从返回文章数组的端点返回的文章数组。但是,我很确定它不能正常工作,因为它总是说数据是有效的,即使我故意不在文章中包含必填字段。
如何根据架构正确验证数据数组?
完整的测试代码在下面作为独立的可运行测试。这两个测试都应该失败,但只有一个失败。
<?php
declare(strict_types=1);
error_reporting(E_ALL);
require_once __DIR__ . '/vendor/autoload.php';
// Return the definition of the schema, either as an array
// or a PHP object
function getSchema($asArray = false)
{
$schemaJson = <<< 'JSON'
{
"swagger": "2.0",
"info": {
"termsOfService": "http://swagger.io/terms/",
"version": "1.0.0",
"title": "Example api"
},
"paths": {
"/articles": {
"get": {
"tags": [
"article"
],
"summary": "Find all articles",
"description": "Returns a list of articles",
"operationId": "getArticleById",
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Article"
}
}
}
},
"parameters": [
]
}
},
"/articles/{articleId}": {
"get": {
"tags": [
"article"
],
"summary": "Find article by ID",
"description": "Returns a single article",
"operationId": "getArticleById",
"produces": [
"application/json"
],
"parameters": [
{
"name": "articleId",
"in": "path",
"description": "ID of article to return",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/Article"
}
}
}
}
}
},
"definitions": {
"Article": {
"type": "object",
"required": [
"id",
"title"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"title": {
"type": "string",
"description": "The title for the link of the article"
}
}
}
},
"schemes": [
"http"
],
"host": "example.com",
"basePath": "/",
"tags": [],
"securityDefinitions": {
},
"security": [
{
"ApiKeyAuth": []
}
]
}
JSON;
return json_decode($schemaJson, $asArray);
}
// Extract the schema of the 200 response of an api endpoint.
function getSchemaForPath($path)
{
$swaggerData = getSchema(true);
if (isset($swaggerData["paths"][$path]['get']["responses"][200]['schema']) !== true) {
echo "response not defined";
exit(-1);
}
return $swaggerData["paths"][$path]['get']["responses"][200]['schema'];
}
// JsonSchema needs to know about the ID used for the top-level
// schema apparently.
function aliasSchema($prefix, $schemaForPath)
{
$aliasedSchema = [];
foreach ($schemaForPath as $key => $value) {
if ($key === '$ref') {
$aliasedSchema[$key] = $prefix . $value;
}
else if (is_array($value) === true) {
$aliasedSchema[$key] = aliasSchema($prefix, $value);
}
else {
$aliasedSchema[$key] = $value;
}
}
return $aliasedSchema;
}
// Test the data matches the schema.
function testDataMatches($endpointData, $schemaForPath)
{
// Setup the top level schema and get a validator from it.
$schemaStorage = new \JsonSchema\SchemaStorage();
$id = 'file://example';
$swaggerClass = getSchema(false);
$schemaStorage->addSchema($id, $swaggerClass);
$factory = new \JsonSchema\Constraints\Factory($schemaStorage);
$jsonValidator = new \JsonSchema\Validator($factory);
// Alias the schema for the endpoint, so JsonSchema can work with it.
$schemaForPath = aliasSchema($id, $schemaForPath);
// Validate the things
$jsonValidator->check($endpointData, (object)$schemaForPath);
// Process the result
if ($jsonValidator->isValid()) {
echo "The supplied JSON validates against the schema definition: " . \json_encode($schemaForPath) . " \n";
return;
}
$messages = [];
$messages[] = "End points does not validate. Violations:\n";
foreach ($jsonValidator->getErrors() as $error) {
$messages[] = sprintf("[%s] %s\n", $error['property'], $error['message']);
}
$messages[] = "Data: " . \json_encode($endpointData, JSON_PRETTY_PRINT);
echo implode("\n", $messages);
echo "\n";
}
// We have two data sets to test. A list of articles.
$articleListJson = <<< JSON
[
{
"id": 19874
},
{
"id": 19873
}
]
JSON;
$articleListData = json_decode($articleListJson);
// A single article
$articleJson = <<< JSON
{
"id": 19874
}
JSON;
$articleData = json_decode($articleJson);
// This passes, when it shouldn't as none of the articles have a title
testDataMatches($articleListData, getSchemaForPath("/articles"));
// This fails correctly, as it is correct for it to fail to validate, as the article doesn't have a title
testDataMatches($articleData, getSchemaForPath("/articles/{articleId}"));
最小的 composer.json 是:
{
"require": {
"justinrainbow/json-schema": "^5.2"
}
}
解决方案
编辑 2:5 月 22 日
我一直在进一步挖掘问题是因为您的顶级转换为object
$jsonValidator->check($endpointData, (object)$schemaForPath);
你不应该这样做,而且一切都会奏效
$jsonValidator->check($endpointData, $schemaForPath);
所以它似乎不是一个错误,它只是一个错误的用法。如果您只是删除(object)
并运行代码
$ php test.php
End points does not validate. Violations:
[[0].title] The property title is required
[[1].title] The property title is required
Data: [
{
"id": 19874
},
{
"id": 19873
}
]
End points does not validate. Violations:
[title] The property title is required
Data: {
"id": 19874
}
编辑-1
要修复原始代码,您需要更新CollectionConstraints.php
/**
* Validates the items
*
* @param array $value
* @param \stdClass $schema
* @param JsonPointer|null $path
* @param string $i
*/
protected function validateItems(&$value, $schema = null, JsonPointer $path = null, $i = null)
{
if (is_array($schema->items) && array_key_exists('$ref', $schema->items)) {
$schema->items = $this->factory->getSchemaStorage()->resolveRefSchema((object)$schema->items);
var_dump($schema->items);
};
if (is_object($schema->items)) {
这肯定会处理您的用例,但如果您不喜欢从依赖项中更改代码,请使用我的原始答案
原始答案
该库有一个错误/限制,即src/JsonSchema/Constraints/CollectionConstraint.php
它们不能$ref
像这样解析变量。如果我像下面这样更新您的代码
// Alias the schema for the endpoint, so JsonSchema can work with it.
$schemaForPath = aliasSchema($id, $schemaForPath);
if (array_key_exists('items', $schemaForPath))
{
$schemaForPath['items'] = $factory->getSchemaStorage()->resolveRefSchema((object)$schemaForPath['items']);
}
// Validate the things
$jsonValidator->check($endpointData, (object)$schemaForPath);
并再次运行它,我得到了所需的异常
$ php test2.php
End points does not validate. Violations:
[[0].title] The property title is required
[[1].title] The property title is required
Data: [
{
"id": 19874
},
{
"id": 19873
}
]
End points does not validate. Violations:
[title] The property title is required
Data: {
"id": 19874
}
您需要修复CollectionConstraint.php
或向 repo 的开发人员提出问题。或者$ref
在整个架构中手动替换您的,如上所示。我的代码将解决特定于您的架构的问题,但修复任何其他架构应该不是一个大问题
推荐阅读
- django - 为什么我们在表单中使用获取用户模型
- twilio - 在 Twilio 视频 JavaScript API 中,如何获取本地参与者的 SID?
- modelica - 无法在 Dymola 中生成平面 Modelica 代码?
- amazon-web-services - 降低 AMI 快照的成本
- python - 在 Python 中使用 Gekko 运行时间序列线性优化
- python - 在python中迭代大型csv文件中的行的最佳方法,写入新的
- python-3.x - 如何使用 OpenCV Python 遮蔽圆圈外的区域?
- machine-learning - YOLO 中的联合交叉 (IOU) 基本事实
- python - Google Chrome 扩展程序不显示我的图标(Selenium 模式,没有 GOOGLE WEBSTORE)
- google-cloud-platform - 为什么 Google Cloud Debugger 不能自动检测我的源代码?