blancks / fast-jsonpatch-php
根据RFC 6902规范设计的类,用于高效处理JSON Patch操作
Requires
- php: >=8.1
Requires (Dev)
- phpstan/phpstan: ^1.11
- phpunit/phpunit: ^10
README
FastJsonPatch根据RFC 6902规范设计,用于处理JSON Patch操作。
JSON Patch是一种用于表示对JSON文档应用的一系列操作的格式。此类提供了解析、验证和应用这些操作的方法,允许您以编程方式修改JSON对象或数组。
通过Composer安装
composer require blancks/fast-jsonpatch-php
基准测试结果
以下表格显示了每个库将补丁应用于目标文档所需平均时间,作为性能总结。基准测试脚本和完整数据可在blancks/php-jsonpatch-benchmarks找到。
发布之间的性能比较仍然可用这里
关键特性
-
应用JSON Patch操作
- 该类可以将一系列JSON Patch操作应用于目标JSON文档。
- 操作按顺序执行,根据补丁修改文档。
-
操作类型
- add: 在JSON文档的特定位置添加一个值。
- copy: 在JSON文档内将一个值从一处复制到另一处。
- move: 在JSON文档内将一个值从一个位置移动到另一个位置。
- remove: 从JSON文档的特定位置删除一个值。
- replace: 将JSON文档中特定位置的值替换为新值。
- test: 测试在JSON文档的特定位置是否存在指定的值。
-
路径解析
- 该类使用JSON Pointer (RFC 6901) 表示法来识别JSON文档内的位置。它正确处理路径语法,包括转义特殊字符等边缘情况。
-
验证
- 该类确保提供的补丁文档符合JSON Patch规范,在应用之前验证结构和操作类型。
-
性能
- 该类针对性能进行了优化,时间复杂度为O(N*P),其中N是补丁中的操作数量,P是补丁操作嵌套级别。
- 最佳使用场景是当JSON文档可以完全加载到内存中,并且需要快速补丁处理,如WebSocket服务器/客户端。
-
测试
- 广泛的单元测试确保一切稳健且按预期工作。
基本用法
<?php require_once 'vendor/autoload.php'; use blancks\JsonPatch\FastJsonPatch; use blancks\JsonPatch\FastJsonPatch\exceptions\FastJsonPatchException; $json = '{"name": "John", "age": 30}'; $patch = '[ {"op": "replace", "path": "/name", "value": "Jane"}, {"op": "add", "path": "/email", "value": "jane@example.com"} ]'; try { echo FastJsonPatch::apply($json, $patch); // Output: {"name": "Jane", "age": 30, "email": "jane@example.com"} } catch(FastJsonPatchException $e) { // FastJsonPatchException comes with two additional methods to fetch context data: // $e->getContextPointer() may return the context JSON pointer for given error // $e->getContextDocument() may return the portion of the document relevant for the error }
方法概述
-
apply(string $json, string $patch): string
将$patch操作应用于提供的$json文档,并返回更新后的JSON文档字符串。 -
applyDecoded(string $json, string $patch): mixed
与apply
相同,但返回解码的文档而不是JSON字符串 -
applyByReference(array|\stdClass &$document, array $patch): void
引用内存中的文档表示,就地应用补丁。 -
parsePath(string $json, string $pointer): mixed
返回从$json字符串文档中根据给定的$pointer找到的值 -
parsePathByReference(array|\stdClass &$document, string $pointer): mixed
与 parsePath 相同,但查找的是内存中文档的位置 -
validatePatch(string $patch): void
检查提供的 $patch 结构是否有效
运行测试
composer test
测试案例来自 json-patch/json-patch-tests 并进一步扩展。
许可证
本软件受 MIT 许可证 许可。