remorhaz/php-json-patch

JSON Patch (RFC-6902) PHP实现

v0.6.1 2024-02-21 21:30 UTC

This package is auto-updated.

Last update: 2024-09-21 22:37:39 UTC


README

Latest Stable Version Build Scrutinizer Code Quality codecov Mutation testing badgeTotal Downloads License

此库实现了符合RFC6902规范的JSON补丁工具。

需求

安装

您需要composer来进行安装。

composer require remorhaz/php-json-patch

文档

访问JSON文档

您可以从编码的JSON字符串或使用相应的节点值工厂从解码的JSON数据创建可访问的JSON文档。

use Remorhaz\JSON\Data\Value\EncodedJson;
use Remorhaz\JSON\Data\Value\DecodedJson;

// Creating document from JSON-encoded string:
$encodedValueFactory = EncodedJson\NodeValueFactory::create();
$encodedJson = '{"a":1}';
$document1 = $encodedValueFactory->createValue($encodedJson);

// Creating document from decoded JSON data:
$decodedValueFactory = DecodedJson\NodeValueFactory::create();
$decodedJson = (object) ['a' => 1];
$document2 = $decodedValueFactory->createValue($decodedJson);

创建和查询处理

您应该使用查询工厂从JSON补丁文档创建查询。然后您应该使用处理器应用该查询。

<?php
use Remorhaz\JSON\Data\Value\EncodedJson;
use Remorhaz\JSON\Patch\Processor\Processor;
use Remorhaz\JSON\Patch\Query\QueryFactory;

$encodedValueFactory = EncodedJson\NodeValueFactory::create();
$queryFactory = QueryFactory::create();
$processor = Processor::create();

$patch = $encodedValueFactory->createValue('[{"op":"remove","path":"/0"}]');
$query = $queryFactory->createQuery($patch);

$document = $encodedValueFactory->createValue('[1,2]');
$result = $processor->apply($query, $document);

var_dump($result->encode()); // string: '[2]'
var_dump($result->decode()); // array: [2]

请注意,结果可以导出为JSON编码的字符串或原始PHP值。

许可

PHP JSON Patch采用MIT许可