
opis/json-schema进行严格的数据验证,这很好地保证了数据的质量。但一旦验证失败,返回给客户端的错误信息通常是像{"keyword": "minLength", "pointer": "productName", "message": "The attribute length should be at least 3 characters."}这样的原始技术细节。对于普通用户来说,这些信息过于专业和晦涩,无法提供直观的指引。为了将这些机器友好的错误转化为人类可读的、甚至本地化的提示,我不得不编写大量的转换逻辑,这不仅耗时,也使得代码变得臃肿且难以维护。Composer在线学习地址:学习地址
幸运的是,PHP社区的强大之处在于总有开发者为我们解决痛点。今天,我要向大家介绍一个非常实用的Composer包:m1x0n/opis-json-schema-error-presenter。
重要提示: 需要注意的是,opis/json-schema库的最新版本(2.0.0及以上)可能已经内置了错误格式化功能,这意味着m1x0n/opis-json-schema-error-presenter在未来可能会变得不那么必要。但对于目前正在使用旧版本opis/json-schema,或者需要更高度定制化错误呈现方式的项目来说,这个库仍然是不可多得的利器。
m1x0n/opis-json-schema-error-presenter是一个专门用于将Opis\JsonSchema\ValidationError对象转换为人类可读的、结构化的错误信息的库。它让我们可以轻松地将那些冰冷的验证失败信息,转化为用户友好的提示,极大地提升了用户体验和开发效率。
首先,通过Composer安装这个库:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
<code class="bash">composer require m1x0n/opis-json-schema-error-presenter</code>
安装完成后,你可以像下面这样使用它来美化你的验证错误:
<pre class="brush:php;toolbar:false;"><?php
require __DIR__ . '/vendor/autoload.php';
use Opis\JsonSchema\Schema;
use Opis\JsonSchema\Validator;
use OpisErrorPresenter\Implementation\MessageFormatterFactory;
use OpisErrorPresenter\Implementation\PresentedValidationErrorFactory;
use OpisErrorPresenter\Implementation\ValidationErrorPresenter;
use OpisErrorPresenter\Contracts\PresentedValidationError;
// 假设你的JSON Schema和待验证数据
$jsonSchema ='{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Product",
"type": "object",
"properties": {
"productId": { "type": "integer", "minimum": 1 },
"productName": { "type": "string", "minLength": 3 },
"price": {
"type": "object",
"properties": {
"amount": { "type": "integer", "minimum": 0, "maximum": 1000 },
"currency": { "type": "string", "enum": ["USD", "EUR", "BTC"] }
},
"required": ["amount", "currency"]
}
},
"required": [ "productId", "productName", "price" ]
}';
$data = '{
"productId": "123", // 期望整数,实际字符串
"productName": "XX", // 期望最小长度3,实际2
"price": {
"amount": 200,
"currency": "GBP" // 期望USD/EUR/BTC,实际GBP
}
}';
$data = json_decode($data);
$jsonSchema = Schema::fromJsonString($jsonSchema);
$validator = new Validator();
// 获取所有验证错误
$result = $validator->schemaValidation($data, $jsonSchema, -1); // -1 表示获取所有错误
if (!$result->isValid()) {
// 使用 ValidationErrorPresenter 来格式化错误
$presenter = new ValidationErrorPresenter(
new PresentedValidationErrorFactory(
new MessageFormatterFactory()
)
);
// 呈现错误
$presentedErrors = $presenter->present(...$result->getErrors());
// 输出格式化后的错误
echo "验证失败,错误信息如下:\n";
foreach ($presentedErrors as $error) {
/** @var PresentedValidationError $error */
echo "- 字段: " . $error->getPointer() . "\n";
echo " 问题: " . $error->getMessage() . "\n";
echo " 关键词: " . $error->getKeyword() . "\n";
echo "---------------------------\n";
}
// 也可以直接转换为JSON格式输出
echo "\nJSON格式错误输出:\n";
echo json_encode(array_map(static function (PresentedValidationError $error) {
return $error->toArray();
}, $presentedErrors), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} else {
echo "数据验证通过!\n";
}上述代码的输出示例:
<pre class="brush:php;toolbar:false;">验证失败,错误信息如下:
- 字段: productId
问题: The attribute expected to be of type 'integer' but 'string' given.
关键词: type
---------------------------
- 字段: productName
问题: The attribute length should be at least 3 characters.
关键词: minLength
---------------------------
- 字段: price/currency
问题: The attribute must be one of the following values: 'USD', 'EUR', 'BTC'.
关键词: enum
---------------------------
JSON格式错误输出:
[
{
"keyword": "type",
"pointer": "productId",
"message": "The attribute expected to be of type 'integer' but 'string' given."
},
{
"keyword": "minLength",
"pointer": "productName",
"message": "The attribute length should be at least 3 characters."
},
{
"keyword": "enum",
"pointer": "price/currency",
"message": "The attribute must be one of the following values: 'USD', 'EUR', 'BTC'."
}
]告别那些令人头疼的、机器友好的验证错误吧!m1x0n/opis-json-schema-error-presenter为我们提供了一个优雅而强大的解决方案,让你的应用程序能够以更清晰、更友好的方式与用户沟通。如果你正在使用opis/json-schema且需要优化错误呈现,不妨尝试一下这个实用的Composer包!
以上就是告别晦涩难懂的JSON验证错误:使用Composer包m1x0n/opis-json-schema-error-presenter让错误信息更友好的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号