xp-forge / json-patch
实现了RFC #6902中描述的JSON补丁文档
v2.1.0
2024-03-24 11:36 UTC
Requires
- php: >=7.0.0
- xp-framework/core: ^12.0 | ^11.0 | ^10.0 | ^9.0 | ^8.0 | ^7.0
Requires (Dev)
- xp-forge/json: ^5.0 | ^4.0 | ^3.0 | ^2.0
- xp-framework/io-collections: ^10.0 | ^9.0 | ^8.0 | ^7.0
- xp-framework/test: ^2.0 | ^1.0
README
实现了RFC #6902和RFC #6901中描述的JSON补丁文档以及JSON指针。针对RFC #6902和RFC #6901进行测试。更多信息请参阅https://github.com/json-patch/json-patch-tests。也请参阅http://jsonpatch.com/。
示例:JSON补丁
入口类是text.json.patch.Changes
use text\json\patch\{Changes, TestOperation, AddOperation}; // You can create changes via maps... $changes= new Changes( ['op' => 'test', 'path' => '/best', 'value' => 'Choco Liebniz'], ['op' => 'add', 'path' => '/biscuits/1', 'value' => ['name' => 'Ginger Nut']] ); // ...or by using Operation instances $changes= new Changes( new TestOperation('/best', 'Choco Liebniz'), new AddOperation('/biscuits/1', ['name' => 'Ginger Nut']) ); // If you have a JSON patch document, use the spread operator $patch= [ ['op' => 'test', 'path' => '/best', 'value' => 'Choco Liebniz'], ['op' => 'add', 'path' => '/biscuits/1', 'value' => ['name' => 'Ginger Nut']] ]; $changes= new Changes(...$patch);
可用的操作有
AddOperation(string $path, var $value)
- "添加"操作根据目标位置引用执行以下功能之一。RemoveOperation(string $path)
- "删除"操作删除目标位置上的值。ReplaceOperation(string $path, var $value)
- "替换"操作将目标位置上的值替换为新值。MoveOperation(string $from, string $to)
- "移动"操作从指定位置删除值并将其添加到目标位置。CopyOperation(string $from, string $to)
- "复制"操作将指定位置的值复制到目标位置。TestOperation(string $path, var $value)
- "测试"操作测试目标位置上的值是否等于指定值。
要应用更改,请调用apply()
方法并处理结果
$document= [ 'best' => 'Choco Liebniz', 'biscuits' => [ ['name' => 'Digestive'], ['name' => 'Choco Liebniz'] ] ]; $changed= $changes->apply($document); // $changed->successful() := true // $changed->value() := [ // 'best' => 'Choco Liebniz', // 'biscuits' => [ // ['name' => 'Digestive'], // ['name' => 'Ginger Nut'], // ['name' => 'Choco Liebniz'] // ] //];
示例:JSON指针
您还可以在Changes
实例下方使用"原始"功能。
use text\json\patch\Pointer; $document= [ 'biscuits' => [ ['name' => 'Digestive'], ['name' => 'Choco Liebniz'] ] ]; $pointer= new Pointer('/biscuits/1'); // $pointer->exists() := true // $pointer->value() := ['name' => 'Ginger Nut']; // This will return an text.json.patch.Applied instance. Use its isError() // method to discover whether an error occurred. $result= $pointer->modify('Ginger Nut'); // You can chain calls using the then() method. Closures passed to it will // only be invoked if applying the operation succeeds, otherwise an Error // will be returned. $result= $pointer->remove()->then(function() use($pointer) { return $pointer->add('Choco Liebniz'); });